I have a component which is dynamically created with ComponentFactoryResolver
this.container.clear();
let factory = this.resolver.resolveComponentFactory(DynamicComponent);
this.componentRef = this.container.createComponent(factory);
template: '...<child-component [param1]="param1"></child-component>...';
The problem is DynamicComponent's template has child component and input bindings. Is there a way to pass parameters to child component when creating the component dynamically?
Yes like this:
const factory = this.componentFactoryResolver.resolveComponentFactory(LoginComponent);
const component: ComponentRef<LoginComponent> = this.viewContainerRef.createComponent(factory);
component.instance.user = "prop 1";
component.instance.input2 = "prop 2";
Yes, the easiest way to achieve it is:
this.componentRef.instance.param1 = param1;
But pay attention, this solution is prone to errors. If param1 change over time, you can get
EXCEPTION: Expression has changed after it was checked.
which is not easy to debug.
You could want to use a dependency injection solution, as explained in this tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With