【问题标题】:Create Component Dynamically with parameters使用参数动态创建组件
【发布时间】:2018-10-29 22:45:39
【问题描述】:

我有一个使用 ComponentFactoryResolver 动态创建的组件

this.container.clear();
let factory  = this.resolver.resolveComponentFactory(DynamicComponent);
this.componentRef = this.container.createComponent(factory);

template: '...<child-component [param1]="param1"></child-component>...';

问题是 DynamicComponent 的模板有子组件和输入绑定。动态创建组件时有没有办法给子组件传参数?

【问题讨论】:

    标签: angular frontend angular6


    【解决方案1】:

    是这样的:

     const factory = this.componentFactoryResolver.resolveComponentFactory(LoginComponent);
        const component: ComponentRef<LoginComponent> = this.viewContainerRef.createComponent(factory);
        component.instance.user = "prop 1";
        component.instance.input2 = "prop 2";
    

    【讨论】:

    • 这个已经试过了,检查错误后得到表达式已经改变。
    • 尝试添加这个构造函数(private cd: ChangeDetectorRef){} 然后你赋值后,使用this.cd.detectChanges();
    • 什么是this.viewContainerRef
    • @Nehal Jaisalmeria this.viewContainerRef 来自于模板中的 &lt;ng-template #viewContainerRef&gt;&lt;/ng-template&gt; 之类的东西,这是可以动态管理组件的地方,然后在组件代码中提取为 @ViewChild("viewContainerRef", { read: ViewContainerRef }) viewContainerRef: ViewContainerRef; 之类的东西
    【解决方案2】:

    是的,最简单的实现方法是:

    this.componentRef.instance.param1 = param1;
    

    但请注意,此解决方案容易出错。如果 param1 随时间变化,可以得到 ​​p>

    异常:表达式在检查后发生了变化。

    这不容易调试。

    您可能想要使用依赖注入解决方案,如 in this tutorial 所述。

    【讨论】:

    • 这个已经试过了,检查错误后得到表达式已经改变。
    • 您是否按照我链接的依赖注入教程进行操作?
    猜你喜欢
    • 1970-01-01
    • 2020-11-11
    • 2019-06-24
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    相关资源
    最近更新 更多