Week 03 · Day 01 — 建立第一個元件

學習目標

  • 用 CLI 建立元件
  • 看懂 @Component 裝飾器
  • 把元件掛進根元件使用

重點

用 CLI 建立元件

ng generate component hello
# 簡寫
ng g c hello
CLI 會產生 4 個檔案: - hello.component.ts(類別與裝飾器) - hello.component.html(模板) - hello.component.css(樣式) - hello.component.spec.ts(測試)

認識 @Component

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

@Component({
  selector: 'app-hello',              // 使用的標籤名稱
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent {
  message: string = "Hello from Angular!";

  changeMessage(): void {
    this.message = "Message changed!";
  }
}

元件的基本結構 - @Component({...}) 裝飾器告訴 Angular:這是個元件 - selector:在模板中用 <app-hello></app-hello> 使用 - 類別內:屬性 = 畫面資料,方法 = 行為

在根元件使用app.component.html 加上:

<app-hello></app-hello>

實作

  1. my-first-app 執行 ng g c hello
  2. 開啟 hello.component.ts,確認 message 屬性
  3. <app-hello></app-hello> 加到 app.component.html
  4. 在模板顯示:<h2>{{ message }}</h2>

作業

  • 用 CLI 建立 hello 元件
  • 說出元件產生的 4 個檔案
  • 將元件使用在根元件模板中並顯示 message