访问ViewChildren查询列表的第n个子元素(角度) [英] Access nth child of ViewChildren Querylist (Angular)

查看:111
本文介绍了访问ViewChildren查询列表的第n个子元素(角度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问viewchildren查询列表的第n个子项.

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

下面是我的TS:

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

console.log显示更改,第一,最后,长度和_results.

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

如何访问第n个孩子(即第3个孩子,而不是第一个孩子)?

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

当我尝试使用_results(即this.popovers._results [2])执行此操作时,出现错误.

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

谢谢.

推荐答案

实际上,有两种方法可以访问QueryLists

第一种方法:.filter()

您还可以根据自己的喜好使用 .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');

第二种方法:.forEach()

// You can perform any action inside the .forEach() which you can readily access the element
this.popovers.forEach((element, index) => console.log(element));

第三种方法:第一种和最后一种

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

原始数组列表:.toArray()

this.popovers.toArray();    // This will give you the list of popovers caught by your QueryList

这篇关于访问ViewChildren查询列表的第n个子元素(角度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆