1

Is it possible in Angular +2 to do this?

export class AppComponent {

    loadSomething()
    {
        $(.container).append('<app-test></app-test>');
    }
}

If it not, what is the right way?

1 Answer 1

1

Best way is to load component dynamically is to use ComponentFactoryResolver and ViewContainerRef

export class HomeComponent {
    constructor(private componentFactoryResolver: ComponentFactoryResolver,
                private viewContainerRef: ViewContainerRef) {
    }

    private  loadSomething()() {
        const factory = this.componentFactoryResolver.resolveComponentFactory(AppTestComponent);
        const ref = this.viewContainerRef.createComponent(factory);
        ref.changeDetectorRef.detectChanges();
    }
}
  • ComponentFactoryResolver — service used to get the factory of the component we want to inject
  • ViewContainerRef — the container of the parent of our component. createComponent(factory) is the part that actually injects our component into the viewContainerRef that calls it
  • ref — Reference of the component we just injected. We call detectChanges on it so angular will call the necessary lifecycle hooks and start the change detection mechanism.

Check out following link for demo

DEMO

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

4 Comments

Great! but can I send a specific data from load() to home component?
For example if in home.html I have ngFor that reading data[], can I send other data from component to other and append it?
@MarvinEricson : let me give it a try :)
@MarvinEricson: Yes you can pass data check out this demo link

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.