Week 01 · Day 06 — 專案結構:認識根元件

學習目標

  • 看懂根元件 app.component.* 的組成
  • 理解「元件 = 類別 + 模板 + 樣式」
  • 修改模板讓畫面顯示自己的內容

重點

根元件由 3 個檔案組成

檔案 角色
app.component.ts 元件的類別與邏輯(裝飾器 @Component 定義 metadata)
app.component.html 元件的模板(要顯示的畫面)
app.component.css 元件的樣式

app.component.ts 核心

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',      // 在 HTML 中使用 <app-root></app-root>
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-first-app';
}

  • @Component({...}) 是裝飾器,用來把類別變成 Angular 元件
  • selector = 這個元件在 HTML 中的標籤名稱
  • 模板中的 {{ title }} 會顯示類別裡的 title 屬性 → 插值(interpolation)

實作

  1. 開啟 app.component.html
  2. 刪除預設內容,改為:
    <h1>Hello Angular!</h1>
    
  3. 儲存後瀏覽器會自動顯示「Hello Angular!」
  4. 接著試試用插值:
    <h1>{{ title }}</h1>
    
    (先確定 .ts 裡有 title 屬性)

作業

  • 修改 app.component.html,顯示「Hello Angular!」
  • 說明 selector: 'app-root' 的作用
  • 用插值 {{ }} 在模板中顯示一個類別屬性