我正在嘗試從 ngOninit 的查詢列表中觸發元素引用的單擊事件。但是我收到了 forEach 未定義的錯誤消息。我不知道為什么我會收到這樣的錯誤消息。我想觸發 test2 的單擊事件。怎么做?演示:https ://stackblitz.com/edit/angular-ivy-2spfo3?file=src/app/app.component.tsERRORError: Cannot read property 'forEach' of undefinedapp.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(); });}
使用角度 8 從查詢列表中觸發元素引用的點擊事件
尚方寶劍之說
2022-10-13 10:57:42