考虑以下 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()
装饰器来获取 View 中特定组件类型的所有实例的列表:
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
});
}
}
只要在 View 中添加或删除此组件的实例,eventThumbnails
属性就会更新。请注意,eventThumbnails
直到 ngAfterViewInit
才设置。
请参阅此处的文档以获取更多信息: https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html
关于javascript - Angular.js 2 : Access component of a directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42990704/