【发布时间】:2020-06-20 11:40:54
【问题描述】:
我正在尝试从 ngOninit 上的查询列表中触发元素引用的点击事件。但是我收到了 forEach 未定义的错误消息。我不知道为什么我会收到这样的错误消息。我想触发点击事件for test2.怎么做?
演示:https://stackblitz.com/edit/angular-ivy-2spfo3?file=src/app/app.component.ts
ERROR
Error: Cannot read property 'forEach' of undefined
app.component.html:
<div *ngFor="let data of list; let i=index">
<div #el (click)="getVal(data.id)">{{data.name}} </div>
</div>
app.component.ts:
@ViewChildren('el') elList: QueryList<ElementRef>
newindex=1;
list=[
{
name:"test1",
id:1
},
{
name:"test2",
id:2
},
{
name:"test3",
id:3
}
]
getVal(id){
alert("Trigger click for: test"+id);
}
ngOnInit(){
this.elList.forEach((item, index) => {
if (index === (this.newindex - 1)) (item.nativeElement as HTMLElement).click();
});
}
【问题讨论】:
标签: javascript typescript angular7 angular8