簡體   English   中英

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

我的面前沒有電腦,這就是想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM