Create Component Dynamically with parameters

别来无恙 提交于 2021-02-07 14:41:13

问题


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:


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



回答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.



来源:https://stackoverflow.com/questions/50429163/create-component-dynamically-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!