![](/img/trans.png)
[英]how access to the properties of a <form> in Angular.js using a directive
[英]Angular.js 2: Access component of a directive
考慮以下Parent
模板的代碼段:
<div *ngFor= "let event of events" >
<event-thumbnail [theEvent] = 'event'></event-thumbnail>
</div>
event-thumbnail
組件的定義也是:
export class EventThumbnailComponent{
intoroduceYourself(){
console.log('I am X');
}
}
在Parent
組件類中,我要遍歷所有生成的event-thumbnail
元素,訪問每個元素下方的組件,並在其中一個上調用introduceYourself
函數。
您想使用@ViewChildren()
裝飾器來獲取視圖中特定組件類型的所有實例的列表:
class ParentComponent implements AfterViewInit {
@ViewChildren(EventThumbnailComponent)
eventThumbnails: QueryList<EventThumbnailComponent>;
ngAfterViewInit(): void {
// Loop over your components and call the method on each one
this.eventThumbnails.forEach(component => component.introduceYourself());
// You can also subscribe to changes...
this.eventThumbnails.changes.subscribe(r => {
// Do something when the QueryList changes
});
}
}
每當將此組件的一個實例添加到視圖中或從視圖中刪除時, eventThumbnails
屬性都將更新。 注意eventThumbnails
沒有設置直到ngAfterViewInit
。
有關更多信息,請參見此處的文檔: https : //angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html
您的子組件應該具有@Input() theEvent
才能訪問您傳遞的事件。 然后,您可以使用以下生命周期掛鈎:
ngOnInit(){
introduceYourself(){
console.log('I am X');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.