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?
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 injectViewContainerRef — the container of the parent of our component.
createComponent(factory) is the part that actually injects our component into the viewContainerRef that calls itref — 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
load() to home component?