[英]Access nth child of ViewChildren Querylist (Angular)
I'm trying to access the nth child of a viewchildren querylist.我正在尝试访问 viewchildren 查询列表的第 n 个子项。
Below is my TS:下面是我的TS:
@ViewChildren(PopoverDirective) popovers: QueryList<PopoverDirective>;
console.log(this.popovers)
The console.log shows changes, first, last, length and _results. console.log 显示更改、第一个、最后一个、长度和_results。
How can I access the nth child (ie, 3rd, instead of first)?我怎样才能访问第 n 个孩子(即第 3 个,而不是第一个)?
When I try to do this with _results (ie, this.popovers._results[2]), I get an error.当我尝试使用 _results(即 this.popovers._results[2])执行此操作时,出现错误。
Thank you.谢谢你。
There are actually a couple of methods which you can access a particular inside you
QueryLists
实际上有几种方法可以访问
QueryLists
中的特定内容
1st method: .filter()第一种方法:.filter()
You can also use .map and.reduce based on your preferences您还可以根据自己的喜好使用.map 和 .reduce
// 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()第二种方法:.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()原始数组列表:.toArray()
this.popovers.toArray(); // This will give you the list of popovers caught by your QueryList
Accessing by index is possible through Find
可以通过
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.你可以使用 toArray() 方法然后你可以通过索引访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.