简体   繁体   English

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

[英]How can I get children elements from QueryList in Angular 2?

I am newbie at Angular2. 我是Angular2的新手。 In my view I have few identical children that are generated in *ngFor. 在我看来,我有几个相同的孩子在* ngFor中生成。

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

I need to call methods of these components at parent element and find out the ViewChildren decorator and the code is: 我需要在父元素中调用这些组件的方法并找出ViewChildren装饰器,代码是:

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

Then I try to iterate them by forEach: 然后我尝试通过forEach迭代它们:

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

But it does nothing. 但它没有任何作用。 toArray() method called on QueryList returns empty array. 在QueryList上调用的toArray()方法返回空数组。

Any suggestions how can I get all children components at one time and call its methods? 任何建议如何一次获取所有子组件并调用其方法?

If clients is set from an async call (for example to the server) then the elements don't exist in ngAfterViewInit() yet. 如果clients是从异步调用(例如服务器)设置的,那么元素在ngAfterViewInit()不存在。

You can use 您可以使用

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

See also https://angular.io/api/core/QueryList#changes 另请参见https://angular.io/api/core/QueryList#changes

I think you should be using the @ContentChildren attribute instead of the ViewChildren. 我认为您应该使用@ContentChildren属性而不是ViewChildren。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM