Angular 6:获取对在 ng-container 标签内使用 *ngFor 创建的组件的引用
Angular 6: get reference to Components created with *ngFor inside ng-container tag
我正在使用 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 中的引用组件。
我试过用
@ViewChildren('#fieldcmp') 字段列表:查询列表;和
@ContentChildren('#fieldcmp') 字段列表:查询列表;
在父组件内部,但如果我尝试在 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;
或者您可以使用组件 class 作为选择器:
@ViewChildren(HelloComponent) fieldsList: QueryList<HelloComponent>;
在这里工作 stackblitz:https://stackblitz.com/edit/angular-xeudlp
尝试创建并清空 directive
,然后查询您的指令并阅读 ElementRef
。
@ViewChildren(MyDirective, {read: Element Ref})
Kids: QueryList<ElementRef>;
我面前没有电脑,但就是这样。
我正在使用 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 中的引用组件。
我试过用 @ViewChildren('#fieldcmp') 字段列表:查询列表;和 @ContentChildren('#fieldcmp') 字段列表:查询列表; 在父组件内部,但如果我尝试在 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;
或者您可以使用组件 class 作为选择器:
@ViewChildren(HelloComponent) fieldsList: QueryList<HelloComponent>;
在这里工作 stackblitz:https://stackblitz.com/edit/angular-xeudlp
尝试创建并清空 directive
,然后查询您的指令并阅读 ElementRef
。
@ViewChildren(MyDirective, {read: Element Ref})
Kids: QueryList<ElementRef>;
我面前没有电脑,但就是这样。