1

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...

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Still didnt find how to create components dynamically wiyh dependencies

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.