代码之家  ›  专栏  ›  技术社区  ›  Anna Ladyzhenskaya

如何从Angular 2中的QueryList中获取子元素?

  •  27
  • Anna Ladyzhenskaya  · 技术社区  · 8 年前

    <ngb-panel *ngFor="let client of clients" [title]="'Client #' + client.id">
        <template ngbPanelContent>
            <processing-item [client]="client"></processing-item>
        </template>
    </ngb-panel>
    

    @ViewChildren(ProcessingItemComponent) processingItems: QueryList<ProcessingItemComponent>;
    

    然后我尝试用forEach迭代它们:

    ngAfterViewInit() {
        this.processingItems.forEach(function (el) {
            console.log(el);
        });
    }
    

    但它什么也没做。在QueryList上调用的toArray()方法返回空数组。

    2 回复  |  直到 8 年前
        1
  •  41
  •   Günter Zöchbauer    8 年前

    如果 clients ngAfterViewInit() 然而

    您可以使用

    ngAfterViewInit() {
      this.processingItems.changes.subscribe(() => {
        this.processingItems.toArray().forEach(el => {
            console.log(el);
        });
      });
    }
    

    https://angular.io/api/core/QueryList#changes

        2
  •  1
  •   Matthew Parton    7 年前

    我认为应该使用@ContentChildren属性,而不是ViewChildren。

    @ContentChildren( OptionComponent )
    public Options: QueryList<OptionComponent>;