[英]Access to child component reference for Angular @ViewChildren
I'm creating a number of ModuleItemComponents using the following Angular markup:我正在使用以下 Angular 标记创建多个 ModuleItemComponents:
<div #moduleItems *ngFor="let module of seriesItem.modules; let i = index">
<app-module-item [videoModule]="module" ></app-module-item>
</div>
and the following code lives in the corresponding.ts file:以下代码位于对应的.ts 文件中:
@ViewChildren('moduleItems') moduleItems;
I'm using code in the ngAfterViewInit event to try and get a reference to each ModuleItemComponent:我在 ngAfterViewInit 事件中使用代码来尝试获取对每个 ModuleItemComponent 的引用:
ngAfterViewInit() {
let items: [];
items = this.moduleItems.map((m) => m.nativeElement.firstChild);
items.forEach((m) => {
const thisModule = (m as ModuleItemComponent);
thisModule.onSelectionMade.subscribe((result: VideoModule) => {
this.deselectOthers(result);
});
});
}
However, I get an error at the ".subscribe" line because the type of thisModule is app-module-item, not ModuleItemComponent.但是,我在“.subscribe”行出现错误,因为 thisModule 的类型是 app-module-item,而不是 ModuleItemComponent。
I'm sure I'm doing something wrong - just not sure how to do this right.我确定我做错了什么 - 只是不知道如何正确地做到这一点。 Any help appreciated.
任何帮助表示赞赏。
You need put the variable reference in the <app-module-item>
您需要将变量引用放在
<app-module-item>
<app-module-item #moduleItems ...>
But in this case, you can use the own name of the class and forget the variable reference但在这种情况下,您可以使用 class 自己的名称而忘记变量引用
@ViewChildren(ModuleItemComponent) moduleItems:QueryList<ModuleItemComponent>
And you can do你可以做
ngAfterViewInit()
{
this.moduleItems.forEach(item=>{
..item is a ModuleItemComponent..
..you has access to all his properties..
..e.g. item.onSelectionMade.subscribe(....)
})
}
See that the name of the class is not between quotes -I supose the name of the class is ModuleItemComponent, else change for the name of the class-看到 class 的名称不在引号之间-我假设 class 的名称是 ModuleItemComponent,否则更改为类的名称-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.