Access nth child of ViewChildren Querylist (Angular)

南笙酒味 提交于 2020-03-18 10:50:30

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/55737546/access-nth-child-of-viewchildren-querylist-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!