[英]How do I pass multiple parameters to an @Input decorator function in Angular 4
[英]Consuming multiple properties via Input decorator in angular 2
我有這個組件通過其選擇器接收兩個輸入,但這可以擴展到任意數量的輸入和任何組件。 因此,為了在組件本身消耗多個屬性,單個@Input()
裝飾器不允許我使用多個屬性,因此作為一種解決方法我使用了兩個裝飾器用於兩個輸入屬性,但我不認為這將是解決這種情況的唯一方法。
export class AsyncComponent {
@Input() waitFor: boolean;
@Input() message: string; // TODO: Verify if multiple inputs are needed for multiple props
}
更新
<app-async [waitFor]="true" message="foo"><app-async>
那么,是否有可能用任何其他方式只使用一個裝飾器來獲取任意數量的輸入道具? 如果有更多的道具,我路過以外waitFor
和message
我會做的每個支撐以下。
@Input() waitFor: boolean;
@Input() message: string;
@Input() someOtherProp: string;
....
或者有沒有其他方法只有一個Input
裝飾器並消耗任意數量的屬性?
我同意羅曼C.
我只傳遞一個包含所有道具的對象(不是數組):
@Component({
selector: 'app-async'
})
export class AsyncComponent {
// Single object with all props.
@Input() props: { waitFor: boolean; message: string; };
}
然后是父組件:
@Component({
template: '<app-async [props]="myProps"><app-async>'
})
export class ParentComponent {
myProps = { waitFor: true, message: 'foo' };
}
NB。 請注意,在輸入屬性上聲明的接口不是ENFORCED。 最佳做法是仍然聲明它們,但JavaScript無法運行時檢查TypeScript接口。 此注釋適用於此線程中的所有代碼示例(單個輸入,多個輸入...)。
如果您需要多個值使用數組或其他內容,則無法實現
export class AsyncComponent {
@Input() props: any[];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.