且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问ViewChildren查询列表的第n个子元素(角度)

更新时间:2023-02-21 12:26:26

实际上,有两种方法可以访问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