Week 03 · Day 01 — 建立第一個元件
學習目標
- 用 CLI 建立元件
- 看懂
@Component裝飾器 - 把元件掛進根元件使用
重點
用 CLI 建立元件
ng generate component hello
# 簡寫
ng g c hello
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>
實作
- 在
my-first-app執行ng g c hello - 開啟
hello.component.ts,確認message屬性 - 把
<app-hello></app-hello>加到app.component.html - 在模板顯示:
<h2>{{ message }}</h2>
作業
- 用 CLI 建立
hello元件 - 說出元件產生的 4 個檔案
- 將元件使用在根元件模板中並顯示
message