簡體   English   中英

ng-for中的ng-template僅創建1次

[英]ng-template inside ng-for creates only 1 time

我在ngFor使用動態表格加載器angular 6

<div *ngFor="let field of item.fields" >
   <ng-template pf-host ></ng-template>
</div>

問題是ng-template僅在第一次創建。 僅在第一個字段中有4個字段和ng-template。

loadComponents()也有一個循環,例如我的HTML標記。 並創建4次。

loadComponent() {
    this.item.fields.forEach(item => {
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
        const viewContainerRef = this.pfHost.viewContainerRef;
        const componentRef = viewContainerRef.createComponent(componentFactory);
         });
}

如何正確制作? 在第一項的第一部分中,在第二項的第二部分中,等等? 現在,第一項中包含用於組件的信息。 其他項目為空。

編輯:答案

通過使用@ViewChildren解決了這個問題

@ViewChildren(ProductFormDirective) pfHost: QueryList<ProductFormDirective>;

然后在loadComponents()中按索引進行迭代。

        for (let i = 0; i < this.item.fields.length; i++) {
            const item = this.item.fields[i];
            const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
            const pfHostToArray = this.pfHost.toArray();
            const viewContainerRef = pfHostToArray[i].viewContainerRef;
            const componentRef = viewContainerRef.createComponent(componentFactory);
            console.log('component created');
            const inst = <ProductFormInnerComponent>componentRef.instance;
            (<ProductFormInnerComponent>componentRef.instance).metadata = item;
            item.componentRef = componentRef;
        }

我有點you不安,您在這里並未真正針對您的用例使用正確的方法……您想要實現什么,為什么? 從功能上講,我的意思是。

無論如何,您的組件中的for循環將僅找到與pf-host選擇器匹配的第一個子視圖,因此它將僅在第一個子視圖內創建組件。

暫無
暫無

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

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