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?
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();
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With