Angular 6:获取在ng-container标签内使用* ngFor创建的组件的引用

问题描述 投票:0回答:2

我正在使用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();
    });

谢谢你的帮助

angular angular6 ngfor viewchild ng-container
2个回答
4
投票

只需从#选择器中删除ViewChildren标志 - 仅在模板中使用:

@ViewChildren('fieldcmp') fieldsList: QueryList;

或者您可以使用组件类作为选择器:

@ViewChildren(HelloComponent) fieldsList: QueryList<HelloComponent>;

在这里工作stackblitz:https://stackblitz.com/edit/angular-xeudlp


0
投票

尝试创建并清空directive,然后查询您的指令并阅读ElementRef

@ViewChildren(MyDirective, {read: Element Ref}) Kids: QueryList<ElementRef>;

我没有在我面前的电脑,但这是主意。

© www.soinside.com 2019 - 2024. All rights reserved.