Angular 6: get reference to Components created with *ngFor inside ng-container tag

烂漫一生 提交于 2021-01-05 12:00:09

问题


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>

I would to list of References components inside ng-container.

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 -----------------------

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();
    });

thank you to help


回答1:


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>;

Working stackblitz here: https://stackblitz.com/edit/angular-xeudlp




回答2:


Try create and empty directive, then query your Directive and read the ElementRef.

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

I don't have my computer in front of me but that's the idea.



来源:https://stackoverflow.com/questions/52312165/angular-6-get-reference-to-components-created-with-ngfor-inside-ng-container-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!