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?

3
  • With RC6+ there is now .compileComponentAsync .. check one option here stackoverflow.com/q/38888008/1679310 (also with bindings input) Commented Sep 2, 2016 at 9:20
  • @RadimKöhler compileComponentAsync was removed in RC6. With RC6+ there is now compileModuleAndAllComponentsAsync Commented Sep 2, 2016 at 9:25
  • @yurzui, correct.. that's what I am saying Commented Sep 2, 2016 at 9:26

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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ü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.
There is currently none. You need to come up with your own.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.