Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Component Dynamically with parameters

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?

like image 205
Balaji Perumal Avatar asked May 19 '18 20:05

Balaji Perumal


2 Answers

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";
like image 83
David Anthony Acosta Avatar answered Sep 19 '22 10:09

David Anthony Acosta


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.

like image 21
Cristian Traìna Avatar answered Sep 22 '22 10:09

Cristian Traìna