Search code examples
javascripttypescriptangular7angular8

Trigger the click event for element reference from the query list using angular 8


I am trying to trigger the click event for element reference from the query list on ngOninit.But i am getting forEach undefined erroe message.I do not know Why i am getting like this error message.I want to trigger the click event for test2.How do it?

Demo: 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();
    });
}

Solution

  • Your variable elList is not initialized or defined in your code, I don't see elList in your code above, is it incomplete ?

    Ok looking at your stackblitz I found the issue, you are trying to access a view object when the view hasn't finished loading, you shoud implement AfterViewInit in your component and then add the foreach in this method like this:

    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')
        });
    }
    

    It should work now, if you see works in console !