如何* ngFor使用angular2中的模板variables?

主要成分:

HTML

<event-thumbnail *ngFor='let event1 of events' #thumbnail [event2]="event1" (eventClick)='handleEventClicked($event)'>Hello</event-thumbnail> <button class='btn btn-primary' (click)="thumbnail.alertFoo()">alert id</button> <button class='btn btn-primary' (click)='thumbnail.handleClickMe()'>click me!</button> 

事件 – 缩略图提示

  alertFoo(){ alert("id called"); } handleClickMe(){ this.eventClick.emit('foo'); alert('click'); } 

在上面的代码中,当使用* ngFor时,我无法使用缩略图使用button – >模板variables。 没有调用alertFoo和handleClickMe()通过缩略图。 我也试图把它包装在div中,但仍然无法正常工作。 它只适用于当我把整个代码封闭在一个div中的时候,也就是说,也就是说,那些显示不需要的多个button的button。 我想了解ngFor的工作方式是否有一些解决上述问题,我希望事件重复,但button只能显示一次。

为此 ,使用ViewChild 。 这是一个例子。 由于不知道你的组件是如何命名的,所以我在这里使用了虚拟名称。 所以家长:

模板:

 <button (click)="alertFooInChild()">Click</button> 

TS:

 @ViewChild(AppChild) appChild: AppChild; alertFooInChild() { // call the method in the child this.appChild.alertFoo(); } 

这里是一个演示plunker 🙂