亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用角度 8 從查詢列表中觸發元素引用的點擊事件

使用角度 8 從查詢列表中觸發元素引用的點擊事件

尚方寶劍之說 2022-10-13 10:57:42
我正在嘗試從 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();    });}
查看完整描述

1 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

您的變量 elList 沒有在您的代碼中初始化或定義,我在上面的代碼中沒有看到 elList,它是否不完整?


好的,看看你的 stackblitz 我發現了問題,當視圖沒有完成加載時,你試圖訪問一個視圖對象,你應該在你的組件中實現 AfterViewInit,然后在這個方法中添加 foreach,如下所示:


export class AppComponent implements OnInit, AfterViewInit { 

ngAfterViewInit() {

  this.elList.forEach((item, index) => { 

      if (index === (this.newindex - 1)) (item.nativeElement as HTMLElement).click();

      console.log('works')

    });

}

如果您在控制臺中看到作品,它現在應該可以工作了!


查看完整回答
反對 回復 2022-10-13
  • 1 回答
  • 0 關注
  • 73 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號