11

Currently I'm loading some of my components dynamically with this piece of code.

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);
            });
    }

The problem is that MyComponent has some @Input and Output bindings. Is it possible to set this bindings here? How can I achieve that?

Rose Nettoyeur
  • 885
  • 1
  • 16
  • 29

1 Answers1

14

Bindings to inputs and outputs can only be used to components that are statically added to another components template.

In your case you can do it imperatively like

 var cmpRef = this.vcRef.createComponent(factory, 0, injector);
 cmpRef.instance.someInput = value;
 cmpRef.instance.someOutput.subscribe(data => this.data = data);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    Does ngOnChanges() of the instance gets triggered by Angular when adding the input? For me it doesn't. I have to call cmpRef.instance.ngOnChanges() manually. – Rose Nettoyeur Dec 19 '16 at 11:36
  • 2
    No, `ngOnChanges()` is called when `someProp` changes with `[someInput]="someProp"`. Without such a binding `ngOnChanges` won't be called. You can make `someInput` a setter and put the code there. – Günter Zöchbauer Dec 19 '16 at 12:04
  • @GünterZöchbauer In this case we know inputs of the dynamically created component and give inputs as component needs. So what if we create different dynamic components according as a parameter and each dynamic component needs different inputs? There should be a systematic way to pass input parameters from parent to child. – omeralper Feb 26 '17 at 16:16
  • There is currently none. You need to come up with your own. – Günter Zöchbauer Feb 26 '17 at 16:27