请考虑以下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
函数。
答案 0 :(得分:3)
您希望使用angular.module('auction').controller('HomeController',function ($scope, $http) { bla bla })
装饰器获取视图中特定组件类型的所有实例的列表:
@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
。
有关详细信息,请参阅此处的文档: https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html
答案 1 :(得分:0)
您的子组件应具有@Input() theEvent
才能访问您正在传递的事件。然后您可以使用以下生命周期钩子:
ngOnInit(){
introduceYourself(){
console.log('I am X');
}
}