Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 651
Rose Nettoyeur Avatar asked Sep 02 '16 09:09

Rose Nettoyeur


People also ask

What is @input and @output in Angular 2?

The above pattern — passing data in through an “input” property and sending data out through an “output” event — is the primary way to share data between Angular 2 components.

How can you dynamically load the component?

To dynamically load the component, we use the directive as an anchor and create the component into its position in the DOM. The createComponent method requires the component type, not the instance.

Can we create component dynamically in Angular?

If we go by the Angular definition, a factory component Angular is a base class for a factory that can create a component dynamically. Instantiate a factory for a given type of component with resolveComponentFactory(). Use the resulting ComponentFactory. create() method to create a component of that type.


1 Answers

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);
like image 70
Günter Zöchbauer Avatar answered Nov 05 '22 13:11

Günter Zöchbauer