Angular.js 2:指令的访问组件

时间:2017-03-24 03:05:01

标签: javascript angular

请考虑以下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函数。

2 个答案:

答案 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');
   }
}