I'm using dynamic form loader angular 6 inside ngFor
<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. There are 4 fields and ng-template only inside the first one.
loadComponents() also have a loop such as my HTML markup. And creates 4 times.
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(ProductFormDirective) pfHost: QueryList<ProductFormDirective>;
And then in loadComponents() iterate by index.
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? 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.