繁体   English   中英

Angular 2:使用参数@Input和@Output动态加载组件

[英]Angular 2: Load component dynamically with parameters @Input and @Output

目前我正在用这段代码动态加载我的一些组件。

export class ComponentOutlet {

    constructor(
        private vcRef: ViewContainerRef,
        private compiler: Compiler,
        private dataService: DataService
    ) { }

    private _createDynamicComponent() {

        // Some logic to decide which component should be loaded
        return MyComponent;
    }


    ngOnChanges() {

        this.compiler.compileComponentAsync(this._createDynamicComponent())
            .then(factory => {
                const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
                this.vcRef.clear();
                this.vcRef.createComponent(factory, 0, injector);
            });
    }

问题是MyComponent有一些@InputOutput绑定。 是否可以在此处设置此绑定? 我怎样才能做到这一点?

对输入和输出的绑定只能用于静态添加到另一个组件模板的组件。

在你的情况下,你可以这样做

 var cmpRef = this.vcRef.createComponent(factory, 0, injector);
 cmpRef.instance.someInput = value;
 cmpRef.instance.someOutput.subscribe(data => this.data = data);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM