10

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?

1
  • Were you able to find an answer to this? Commented Mar 30, 2023 at 19:47

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Already tried this one and got expression has changed after it was checked error.
Did you follow the dependency injection tutorial that I linked?
7

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

4 Comments

Already tried this one and got expression has changed after it was checked error.
Try to add this constructor(private cd: ChangeDetectorRef){} Then after you assign the values, use this.cd.detectChanges();
what is this.viewContainerRef
@Nehal Jaisalmeria this.viewContainerRef comes from having something like <ng-template #viewContainerRef></ng-template> in the template, which is where the components can be dynamically managed, and then picked up in the components code as something like @ViewChild("viewContainerRef", { read: ViewContainerRef }) viewContainerRef: ViewContainerRef;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.