Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access nth child of ViewChildren Querylist (Angular)

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.

like image 541
user749798 Avatar asked Apr 18 '19 00:04

user749798


Video Answer


3 Answers

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
like image 169
KShewengger Avatar answered Sep 20 '22 06:09

KShewengger


Accessing by index is possible through Find

  @ViewChildren(PopoverDirective) popovers: QueryList<PopoverDirective>;

  public getByIndex(x: number) {
    return this.popovers.find((_, i) => i == x)
  }
like image 7
Rafi Henig Avatar answered Sep 21 '22 06:09

Rafi Henig


you can use toArray() method and then you can access by index.

like image 5
ABOS Avatar answered Sep 21 '22 06:09

ABOS