Access nth child of ViewChildren Querylist (Angular)

user749798 picture user749798 · Apr 18, 2019 · Viewed 16.4k times · Source

I'm trying to access the nth child of a viewchildren querylist.

Below is my TS:

@ViewChildren(PopoverDirective) popovers: QueryList<PopoverDirective>;
console.log(this.popovers)

The console.log shows changes, first, last, length and _results.

How can I access the nth child (i.e., 3rd, instead of first)?

When I try to do this with _results (i.e., this.popovers._results[2]), I get an error.

Thank you.

Answer

KShewengger picture KShewengger · Apr 18, 2019

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