Week 03 · Day 02 — 元件互動:變更資料與事件
學習目標
- 在元件中加入方法
- 用事件綁定觸發方法
- 讓畫面資料跟著改變
重點
元件 = 狀態 + 行為 - 屬性(state):畫面要顯示的資料 - 方法(methods):點按等行為
事件綁定
在模板中用 (click) 綁定點按事件:
<!-- hello.component.html -->
<div class="hello">
<h2>{{ message }}</h2>
<button (click)="changeMessage()">Change Message</button>
</div>
(click)="changeMessage()":點擊時呼叫元件的方法
- 搭配 {{ message }} 插值顯示最新狀態
方法定義(.ts)
export class HelloComponent {
message: string = "Hello from Angular!";
changeMessage(): void {
this.message = "Message changed!";
}
}
執行流程
1. 頁面顯示 message 目前值
2. 使用者點擊按鈕
3. Angular 呼叫 changeMessage()
4. this.message 改變 → Angular 自動更新畫面(資料綁定)
實作
- 確認
hello.component.ts有message+changeMessage() - 模板加上
<h2>{{ message }}</h2>與<button (click)="changeMessage()"> - 在
app.component.html使用<app-hello> - 點擊按鈕,確認文字從「Hello from Angular!」變成「Message changed!」
作業
- 在元件中新增一個方法並用
(click)觸發 - 說明事件綁定的語法
(eventName)=... - 實測點擊後畫面資料確實被更新