I'm trying to create components dynamically using the ComponentFactoryResolver
.
I have a component that has an @input
that holds the component ref and the component inputs.
the problem is when the components are created in the DOM they hold the exact instance data.
is it possible to create the components without them holding the instance state by reference?
class TrimItemsToPopupListComponent implements OnInit, OnDestroy, AfterViewInit {
@Input() component?: {
ref: ComponentType<unknown>,
inputs: Record<string, unknown>[]
};
constructor(
private resolver: ComponentFactoryResolver,
private cd: ChangeDetectorRef
) {}
ngAfterViewInit(): void {
this.componentVC.clear();
this.inputItems.slice(0, this.trimCount).forEach(() => {
const factory = this.resolver.resolveComponentFactory(this.component.ref);
const componentRef = this.componentVC.createComponent(factory);
this.component.inputs.forEach((cmpInput, index) => {
const inputKey = Object.keys(cmpInput)[0] as string;
// @ts-ignore
componentRef.instance[inputKey] = this.component.inputs[index][inputKey];
});
});
this.cd.detectChanges();
}
You could try this:
Brief explanation:
This should create multiple instances of the component, each with its own set of input bindings, rather than sharing the same instance data by reference.