今日目標
了解 Angular Component 是什麼
學會用 CLI 建立新的元件
把 Day 6 的 HTML 拆分成多個元件(Header、Hero、About、Skills、Projects、Contact、Footer)
在 app.component.html 中組裝這些元件
基礎概念:什麼是 Angular Component?
Angular 的畫面基本單位就是 Component(元件)。
每個元件包含三個部分:
.ts → 邏輯程式(控制資料、事件)
.html → 模板(畫面結構)
.scss → 樣式(只作用在這個元件)
👉 這樣每個部分都各自獨立,方便維護。就像樂高積木一樣,網站就是一堆元件拼在一起。
實作:切分元件
我們的履歷網站可以拆成這幾個主要元件:
header → 網站導覽列(名字、選單、主題切換)
hero → 首屏區塊(自我介紹 + 照片)
about → 關於我(文字 + 更多介紹按鈕)
skills → 技能區(清單 + 篩選)
projects → 作品集(卡片清單)
contact → 聯絡我(表單 + 其他聯絡方式)
footer → 頁尾(版權訊息)
在專案目錄輸入:
ng g c components/header
ng g c components/hero
ng g c components/about
ng g c components/skills
ng g c components/projects
ng g c components/contact
ng g c components/footer
這會自動產生像這樣的結構:
src/app/components/
├─ header/
│ ├─ header.component.ts
│ ├─ header.component.html
│ ├─ header.component.scss
│ └─ header.component.spec.ts
├─ hero/
├─ about/
...
header.component.html → 放 裡的 HTML
hero.component.html → 放 Hero 區塊
about.component.html → 放 About 區塊
其他同理
範例:header.component.html
CLI 幫我們自動註冊了元件,所以可以直接用標籤呼叫:
這樣就等於把一個大 HTML 拆成多個「小積木」。
成果
成功用 Angular CLI 建立了 7 個元件
每個元件有自己的 HTML / SCSS 檔案
app.component.html 現在非常乾淨,只剩下組裝用的 標籤
網站在瀏覽器打開後,畫面跟 Day 6 一樣,但結構更清楚了
小心踩雷(初學者常見錯誤)
把 HTML 貼到 index.html
❌ Angular 的 index.html 只有
✅ 要貼的是各元件的 .component.html
忘了在 app.component.html 使用元件
建立元件後如果沒組裝,畫面上什麼都不會出現。
CSS 沒生效
Angular 元件的 .scss 只作用在該元件
如果想全站通用,要放在 styles.scss
元件名稱不一致
使用時要對應正確的 selector,例如 @Component({ selector: 'app-header' }) →
下一步(Day 9 預告)
明天我們要開始學 Angular 的資料綁定 (Data Binding):
用插值({{ }})在模板中顯示變數
在 TS 檔裡定義資料,讓 HTML 自動更新
把 Skills 與 Projects 的清單改成「由程式動態產生」而不是硬寫死在 HTML