Balaji Perumal
Balaji Perumal

Reputation: 850

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?

Upvotes: 10

Views: 20820

Answers (2)

David Anthony Acosta
David Anthony Acosta

Reputation: 4890

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";

Upvotes: 7

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10374

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.

Upvotes: 8

Related Questions