使用@viewchild访问多个viewchildren

Pio*_*ski 96 angular

我创建了一个自定义组件,我放在一个for循环中,例如

<div *ngFor="let view of views">

     <customcomponent></customcomponent>

</div>
Run Code Online (Sandbox Code Playgroud)

其输出将是:

<customcomponent></customcomponent>
<customcomponent></customcomponent>
<customcomponent></customcomponent>
Run Code Online (Sandbox Code Playgroud)

我想知道当这些组件的数量可以变化时,如何使用@viewchild语法或任何其他方法来获取对这些组件的引用

当组件可以给出一个名称,例如

<customcomponent #compID></customcomponent>
Run Code Online (Sandbox Code Playgroud)

我可以参考如下:

@ViewChild('compID') test: CustomComponent
Run Code Online (Sandbox Code Playgroud)

如果不是这种情况,我如何引用它,例如可能使用索引?

(此问题与使用ElementRef无关,因为之前已经提到的其他问题可以通过下面列出的答案看到)此问题涉及访问多个@ViewChild和使用列表查询.

Bee*_*ice 168

使用@ViewChildrenfrom @angular/core来获取组件的引用

模板

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>
Run Code Online (Sandbox Code Playgroud)

零件

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}
Run Code Online (Sandbox Code Playgroud)

l̶i̶v̶e̶̶d̶e̶m̶o̶

  • @SamAlexander你可以使用this.components.toArray()来获取带有#cmp名称的组件数组 (18认同)
  • 它说._results是一个私人功能.还有这个.组件只是一个单一的组件而不是我的列表.你能提供更多帮助吗? (3认同)
  • 它如何处理 Ajax 响应?,@ViewChildren 在 init View 之后触发,但在模型(对于 ngFor)更改之后不会触发。我该如何触发? (2认同)

sil*_*sod 62

将@ViewChildren装饰器与QueryList结合使用.这两个都来自"@ angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

与每个孩子做一些事情看起来像: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

angular.io还有其他文档,具体来说:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts = Parent%20calls%20a%20ViewChild