3

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
cup_of
  • 6,397
  • 9
  • 47
  • 94
  • 1
    you can use `@ViewChildren` check this https://stackoverflow.com/questions/40165294/access-multiple-viewchildren-using-viewchild – Madhawa Priyashantha Feb 26 '19 at 07:50
  • 1
    Possible duplicate of [Access multiple viewchildren using @viewchild](https://stackoverflow.com/questions/40165294/access-multiple-viewchildren-using-viewchild) – Carsten Feb 26 '19 at 07:53

1 Answers1

3

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();
});
}
Nithya Rajan
  • 4,722
  • 19
  • 30
  • 2
    @Bear you can also iterate over a QueryList using for(let item of this.itemName){...}. If only need first element you can use this.itemName.first.nativeElement.focus() – Eliseo Feb 26 '19 at 09:52