我正在使用ng-container迭代列表并创建组件
<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组件。
我试图使用@ViewChildren('#fieldcmp')fieldsList:QueryList;和@ContentChildren('#fieldcmp')fieldsList:QueryList;在父组件内部,但如果我尝试在ngafterViewInit中访问,我没有得到任何元素
ngAfterViewInit() {
this.fieldsList.forEach((child) => { /* some logic....*/});
}
有人可以帮助我吗?谢谢
-----------更新-----------------------
在使用@ViewChildren('fieldcmp')修复后,我有一个ElementRef列表而不是我的AppComponent。我投了它并且所有的工作
this.filedsList
.forEach((child) => { atLeastOneRequired = atLeastOneRequired || (<ReusableFieldComponent> child).isRequired();
});
谢谢你的帮助
只需从#
选择器中删除ViewChildren
标志 - 仅在模板中使用:
@ViewChildren('fieldcmp') fieldsList: QueryList;
或者您可以使用组件类作为选择器:
@ViewChildren(HelloComponent) fieldsList: QueryList<HelloComponent>;
在这里工作stackblitz:https://stackblitz.com/edit/angular-xeudlp
尝试创建并清空directive
,然后查询您的指令并阅读ElementRef
。
@ViewChildren(MyDirective, {read: Element Ref})
Kids: QueryList<ElementRef>;
我没有在我面前的电脑,但这是主意。