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

use*_*798 8 viewchild angular

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

以下是我的TS:

@ViewChildren(PopoverDirective) popovers: QueryList<PopoverDirective>;
console.log(this.popovers)
Run Code Online (Sandbox Code Playgroud)

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

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

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

谢谢。

KSh*_*ger 10

实际上,您可以使用几种方法来访问内部的特定对象 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');
Run Code Online (Sandbox Code Playgroud)

第二种方法:.forEach()

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

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

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
Run Code Online (Sandbox Code Playgroud)

原始数组列表:.toArray()

this.popovers.toArray();    // This will give you the list of popovers caught by your QueryList
Run Code Online (Sandbox Code Playgroud)


Raf*_*nig 9

通过索引访问可以通过Find

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

  public getByIndex(x: number) {
    return this.popovers.find((_, i) => i == x)
  }
Run Code Online (Sandbox Code Playgroud)

  • 我实际上发现这个方法比调用`toArray()`更快。`toArray()` 在访问索引之前创建底层查询列表的切片。同时,“find()”对原始底层查询列表数组进行操作。因此,它不仅更快,而且会节省一些内存。 (3认同)

ABO*_*BOS 5

您可以使用 toArray() 方法,然后您可以通过索引访问。