Angular 6:在ng-container标签内获取使用* ngFor创建的组件的引用 [英] 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:在ng-container标签内获取使用* ngFor创建的组件的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!