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

Ros*_*eur 9 angular

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

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);
            });
    }
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 11

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

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

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

  • 添加输入时,Angular是否会触发实例的ngOnChanges()?对我而言,事实并非如此.我必须手动调用cmpRef.instance.ngOnChanges(). (2认同)
  • 不,当`someProp`随`[someInput] ="someProp"`改变时,调用`ngOnChanges()`.如果没有这样的绑定,将不会调用`ngOnChanges`.您可以将`someInput`设置为setter并将代码放在那里. (2认同)