0

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

1 Answer 1

1

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 !

Sign up to request clarification or add additional context in comments.

7 Comments

Initialized.Please check @ViewChildren('el') elList: QueryList<ElementRef>
Please check my stackblitz
You're welcome, good luck with your work, have a nice day
Can you add css with trigger clicked event? stackblitz.com/edit/angular-ivy-qoq5tf?file=src/app/…
You can add css dynamically by using [ngClass]='this.classes' on the element you wish to add a css class or [ngStyle]='this.pureCss' for pure css, or if you want to trigger a class with a boolean just add [style.your-class-to-trigger]='this.isChecked'
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.