简体   繁体   English

ng-for中的ng-template仅创建1次

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

I'm using dynamic form loader angular 6 inside ngFor 我在ngFor使用动态表格加载器angular 6

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

And the problem is ng-template creates only in first time. 问题是ng-template仅在第一次创建。 There are 4 fields and ng-template only inside the first one. 仅在第一个字段中有4个字段和ng-template。

loadComponents() also have a loop such as my HTML markup. loadComponents()也有一个循环,例如我的HTML标记。 And creates 4 times. 并创建4次。

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

How can I make it correctly? 如何正确制作? In the first item first component, in second item second component etc? 在第一项的第一部分中,在第二项的第二部分中,等等? Now there are for components in the first item. 现在,第一项中包含用于组件的信息。 Other items are empty. 其他项目为空。

EDIT: ANSWER 编辑:答案

Solved this by using @ViewChildren 通过使用@ViewChildren解决了这个问题

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

And then in loadComponents() iterate by index. 然后在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;
        }

I have a nagging feeling you are not really using the right approach for your use case here... What are you trying to achieve, and why? 我有点you不安,您在这里并未真正针对您的用例使用正确的方法……您想要实现什么,为什么? Functionally I mean. 从功能上讲,我的意思是。

Anyhow, your for loop in your component will only find the first view-child matching the pf-host selector, so it will create components inside the first one only. 无论如何,您的组件中的for循环将仅找到与pf-host选择器匹配的第一个子视图,因此它将仅在第一个子视图内创建组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM