【问题标题】:Trigger the click event for element reference from the query list using angular 8使用角度 8 从查询列表中触发元素引用的点击事件
【发布时间】: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


    【解决方案1】:

    您的变量 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')
        });
    }
    

    如果您在控制台中看到作品,它现在应该可以工作了!

    【讨论】:

    • 已初始化。请检查@ViewChildren('el') elList: QueryList
    • 请检查我的stackblitz
    • 不客气,祝你工作顺利,祝你有美好的一天
    • 可以添加带有触发点击事件的css吗? stackblitz.com/edit/angular-ivy-qoq5tf?file=src/app/…
    • 您可以通过在要添加 css 类的元素上使用 [ngClass]='this.classes' 来动态添加 css,对于纯 css,可以使用 [ngStyle]='this.pureCss',或者如果你想用布尔值触发一个类,只需添加 [style.your-class-to-trigger]='this.isChecked'
    猜你喜欢
    • 2020-07-19
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2020-09-15
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    相关资源
    最近更新 更多