dfloriano
dfloriano

Reputation: 13

Angular 4 - insert a instantiated component dynamically in container

I want to create a dynamic components and insert other components in runtime.

I used ViewContainerRef to solve this problem:

import { MyComponent } from "./component-path";

@Component({
    template: `<ng-template #container></ng-template>`
})
export class GeneralDataComponent implements OnInit {

        @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;    

        constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

        ngOnInit() {
            this.addComponent();
        }

        addComponent() {
            const componentFactory = 
            this.componentFactoryResolver.resolveComponentFactory(MyComponent);
            const component = this.container.createComponent(componentFactory);
        }
}

My component class:

@Component({
    selector: "s-my-component",
    template: require("./mycomponent.html")
})
export class MyComponent implements OnInit {

    constructor(private myVariable: String) { }

    ngOnInit() {
        this.buildSomething(this.variable);
    }

    buildSomething(variable : string) {
        //some logic here
    }
}

That works fine, MyComponent is placed at the container, but I need set value for myVariable to him work properly.

How can I do that?

I don't want to create an amount of components to any possible value of myVariable logic.

There's another way to insert components dynamically with Angular 4 or there's a better way to use the @ViewChild? I'm new to Angular, any sugestions...

Upvotes: 1

Views: 825

Answers (1)

Oleksandr Poshtaruk
Oleksandr Poshtaruk

Reputation: 2166

Just assign prop for instance

Try to use inputs for the logic

  addComponent() {
        const componentFactory = 
         this.componentFactoryResolver.resolveComponentFactory(MyComponent);
        const component = this.container.createComponent(componentFactory);
      component.myVariable = blabla
    }

And put this.buildSomething(this.variable); in ngOnChange.

Upvotes: 1

Related Questions