@Input 裝飾器
概述
在 Angular 中,@Input
裝飾器是實現父組件向子組件傳遞數據的主要方式。這個機制類似於其他框架(如 React)中的 props 概念。
基本語法
1. 在子組件中定義輸入屬性
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-user',
template: `
<p>The user's name is {{ occupation }}</p>
`
})
export class UserComponent {
@Input() occupation = ''; // 定義一個輸入屬性
}
2. 在父組件中傳遞數據
@Component({
selector: 'app-root',
template: `
<app-user [occupation]="jobTitle"></app-user>
`
})
export class AppComponent {
jobTitle = 'Angular Developer';
}
屬性綁定方式
1. 靜態值傳遞(不使用 [])
<app-user occupation="Angular Developer"></app-user>
只能傳遞靜態字符串
值被當作純文本處理
不支持動態更新
2. 動態綁定(使用 [])
<app-user [occupation]="jobTitle"></app-user>
可傳遞變量值
支持表達式
支持動態更新
值會被 Angular 解析和計算
使用 @Input 和不使用的區別
使用 @Input
export class UserComponent {
@Input() occupation = ''; // 可從父組件接收值
}
允許從父組件接收數據
支持組件間通信
屬性值可從外部更新
不使用 @Input
export class UserComponent {
occupation = ''; // 僅組件內部可用
}
僅能在組件內部使用
無法從父組件接收數據
屬性值只能在組件內部修改
實際應用示例
// user.component.ts
@Component({
selector: 'app-user',
template: `
<p>The user's occupation is {{ occupation }}</p>
`,
standalone: true
})
export class UserComponent {
@Input() occupation = '';
}
// app.component.ts
@Component({
selector: 'app-root',
template: `
<app-user [occupation]="currentJob"></app-user>
<button (click)="updateJob()">Update Job</button>
`,
standalone: true,
imports: [UserComponent]
})
export class AppComponent {
currentJob = 'Developer';
updateJob() {
this.currentJob = 'Senior Developer'; // 子組件會自動更新
}
}
最佳實踐
總是為
@Input
屬性提供默認值根據數據類型選擇合適的綁定方式
使用適當的命名約定,確保代碼可讀性
考慮使用類型定義增加代碼健壯性
注意事項
@Input
裝飾器需要從@angular/core
導入屬性綁定是單向的,從父組件到子組件
如需雙向綁定,考慮使用
[(ngModel)]
或配合@Output
確保在
standalone: true
的情況下正確導入相關組件
Last updated