Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate viewChild with same name in ngFor

Tags:

angular

In my html component, I have an *ngFor loop which generates multiple elements like so:

<div *ngFor="let item of items">
  <p #itemName>{{item.name}}</p>
</div>

And in my .ts component to access the <p>, I'm doing:

@ViewChild('itemName') itemName: ElementRef;

And as an example of me doing something with it:

this.itemName.nativeElement.focus();

My issue is that since there can be multiple p tags, there will be multiple instances of itemName in the .ts file and when trying to do something with it, such as the example above, the first instance of itemName will be focused.

How can I determine which instance of itemName I'm currently on?

like image 580
cup_of Avatar asked Oct 22 '25 12:10

cup_of


1 Answers

You can use @viewChildren to select multiple elements with same template reference variables. You should convert the QueryList to array using toArray() method in order to loop over the elements.

import { ViewChildren, QueryList } from '@angular/core';

....

@ViewChildren('itemName') itemName: QueryList<ElementRef>;

ngAfterViewInit() {
  this.itemName.toArray().forEach(el => {
    el.nativeElement.focus();
});
}
like image 183
Bear Nithi Avatar answered Oct 26 '25 11:10

Bear Nithi