主要组件:
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 ie 时,我无法使用缩略图 -> 模板变量来使用按钮。不会通过缩略图调用alertFoo 和handleClickMe()。我也尝试将它包装在 div 内,但仍然不起作用。仅当我将整个代码包含在带有 *ngFor 的 div 中时,它才有效,即还有显示不需要的多个按钮的按钮。我想了解 ngFor 的工作原理是否有一些解决方案可以解决上述问题,我希望事件重复但按钮仅显示一次。
最佳答案
使用ViewChild以此目的。这是一个例子。由于不确切知道您的组件是如何命名的,我在这里使用虚拟名称。所以家长:
模板:
<button (click)="alertFooInChild()">Click</button>
TS:
@ViewChild(AppChild) appChild: AppChild;
alertFooInChild() {
// call the method in the child
this.appChild.alertFoo();
}
这是一个demo plunker :)
关于javascript - *ngFor 如何使用 Angular 2 中的模板变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739113/