【问题标题】:Access nth child of ViewChildren Querylist (Angular)访问 ViewChildren Querylist (Angular) 的第 n 个子项
【发布时间】:2019-09-08 06:58:12
【问题描述】:

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

以下是我的 TS:

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

console.log 显示更改,first、last、length 和 _results。

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

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

谢谢。

【问题讨论】:

    标签: angular viewchild


    【解决方案1】:

    实际上有几种方法可以访问你内部的特定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
    

    【讨论】:

    • 过滤器不返回数组吗?
    • 嗨@QianChen,过滤器确实返回一个数组。
    • 非常感谢您的澄清。如果我想遍历 QueryList&lt;ElementRef&gt; 怎么办?这有什么改变吗? (我现在很难做到这一点,但可能错过了一些明显的东西)。
    • 嗨@Crowdpleasr,即使我们要在元素中查询列表,您仍然可以应用它们。附上 Stackblitz 演示供您参考 - 您可以检查控制台。 stackblitz.com/edit/ngx-viewchildren-querylist
    • toArray() 每次都会创建一个底层查询列表结果的切片。性能方面需要注意的事项。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      通过Find可以通过索引访问

        @ViewChildren(PopoverDirective) popovers: QueryList<PopoverDirective>;
      
        public getByIndex(x: number) {
          return this.popovers.find((_, i) => i == x)
        }
      

      【讨论】:

      • 其实我发现这个方法比调用toArray()还要快。 toArray() 在访问索引之前创建底层查询列表的切片。同时,find() 对原始底层查询列表数组进行操作。因此,它不仅速度更快,而且会节省一些内存。
      猜你喜欢
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 2019-05-31
      • 2022-11-21
      • 2021-12-11
      • 1970-01-01
      • 2018-11-28
      • 2017-03-19
      相关资源
      最近更新 更多