Dynamically load a component in Angular 2 using a selector

Is it possible to dynamically load a component in Angular 2 using a selector ?

Let's say we have a component like below

@Component({ moduleId: module.id, selector: 'my-component', templateUrl: 'my-component.html', styleUrls: ['my-component.css'] }) export class MyComponent{ } 

Can we load this dynamically into a container using its my-component selector

 <div #container ></div> LoadComponent(selector: string){ // Load using selector? } 

It may be necessary to export components to NgModule and import NgModule where we want to load it.

Not sure how to do this, any pointers in the right direction will be very helpful.

Thanks in advance!

+1
source share
2 answers

Well, I was able to solve this using below,

 constructor(private _compiler: Compiler) {} loadComponent = (selector: string, module: any): void => { this._compiler.compileModuleAndAllComponentsAsync(module).then(_module => { let _componentFactories = _module.componentFactories.filter(_c => { // here I am using the selector return _c.selector === selector; }); // check if component is available in the module if (!!_componentFactories && _componentFactories.length > 0) { self.testComponentContainer.clear(); self.testComponentContainer.createComponent(_componentFactories[0]).instance; } }); } 

Hope this helps someone .. !!!

-2
source

You can dynamically load any component using ComponentResolver.
Add the following html node template to the parent template

 <div #node></div> 

And your component will look like

 import { Component, ViewContainerRef, ViewChild, ComponentFactory, ComponentResolver } from '@angular/core'; import { MyComponent} from 'components/my.component'; @Component({ selector: 'app-home', template: `<h2>Home</h2> <div #node></div> ` }) export class HomeComponent implements OnInit { @ViewChild("node", { read: ViewContainerRef }) nodeView; instance: MyComponent constructor(private componentResolver: ComponentResolver) { } ngOnInit(): void { this.componentResolver.resolveComponent(MyComponent) .then((factory: ComponentFactory<MyComponent>) => { this.instance = this.nodeView.createComponent(factory); }); } } 
-2
source

Source: https://habr.com/ru/post/1264850/


All Articles