Angular 6:获取对使用 *ngFor 在 ng-container 标签内创建的组件的引用 [英] Angular 6: get reference to Components created with *ngFor inside ng-container tag
问题描述
我使用 ng-container 迭代列表并创建组件
I'using ng-container to iterate on a list and create components
<ng-container *ngFor="let f of optionsList; let i = index;">
<!-- component-->
<app-component #fieldcmp *ngIf="isAppComponent(f)" ></app-field>
<!--another components-->
<app-anoter-component1 *ngIf="isAnotherComponent1(f)"> </app-anoter-component1>
...
<app-anoter-componentn *ngIf="isAnotherComponentn(f)"> </app-anoter-componentn>
</ng-container>
我想列出 ng-container 中的 References 组件.
I would to list of References components inside ng-container.
我尝试使用@ViewChildren('#fieldcmp') fieldsList: QueryList;和@ContentChildren('#fieldcmp') fieldsList: QueryList;在父组件内部,但如果我尝试在 ngafterViewInit 中访问,我将没有任何元素
I tried to use @ViewChildren('#fieldcmp') fieldsList: QueryList; and @ContentChildren('#fieldcmp') fieldsList: QueryList; inside father component but i get no elements if I try to acces in ngafterViewInit
ngAfterViewInit() {
this.fieldsList.forEach((child) => { /* some logic....*/});
}
有人可以帮助我吗?谢谢
Can someone can help me? Thanks
-----------更新 ---------------
-----------Update -----------------------
使用@ViewChildren('fieldcmp') 修复后,我有一个 ElementRef 列表,而不是我的 AppComponent.我投了它和所有的工作
after fix with @ViewChildren('fieldcmp') I have a list of ElementRef instead of my AppComponent. I cast it with and all work
this.filedsList
.forEach((child) => { atLeastOneRequired = atLeastOneRequired || (<ReusableFieldComponent> child).isRequired();
});
谢谢你的帮助
推荐答案
只需从 ViewChildren
选择器中删除 #
符号 - 仅在模板中使用:>
Just remove the #
sign from your ViewChildren
selector - that is used only in templates:
@ViewChildren('fieldcmp') fieldsList: QueryList;
或者你可以使用组件类作为选择器:
Or you could use component class as a selector:
@ViewChildren(HelloComponent) fieldsList: QueryList<HelloComponent>;
在这里工作 stackblitz:https://stackblitz.com/edit/angular-xeudlp
Working stackblitz here: https://stackblitz.com/edit/angular-xeudlp
这篇关于Angular 6:获取对使用 *ngFor 在 ng-container 标签内创建的组件的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!