我创建了一个自定义组件,我放在一个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)
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
| 归档时间: |
|
| 查看次数: |
68565 次 |
| 最近记录: |