Access nth child of ViewChildren Querylist (Angular)
Accessing by index is possible through Find
@ViewChildren(PopoverDirective) popovers: QueryList<PopoverDirective>;
public getByIndex(x: number) {
return this.popovers.find((_, i) => i == x)
}
you can use toArray() method and then you can access by index.
There are actually a couple of methods which you can access a particular inside you
QueryLists
1st method: .filter()
You can also use .map and .reduce based on your preferences
// Since if you have 3 items in an array, the counting starts at 0, so 1 is the 2nd element
const elementTwo = this.popovers.filter((element, index) => index === 1);
// Or if you want to be specific based on the data inside the PopoverDirective
// and if that PopoverDirective has an @Input() name, you can access it by:
const elementTwo = this.popovers.filter((element, index) => element.name === 'John');
2nd method: .forEach()
// You can perform any action inside the .forEach() which you can readily access the element
this.popovers.forEach((element, index) => console.log(element));
3rd method: first and last
this.popovers.first // This will give you the first element of the Popovers QueryList
this.popovers.last // This will give the last element of the Popovers QueryList
Raw Array List: .toArray()
this.popovers.toArray(); // This will give you the list of popovers caught by your QueryList