Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load component dynamically in Angular 2 using selector

Tags:

angular

Can we load component dynamically in Angular 2 using it's selector?

Lets 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 it's selector my-component

<div #container ></div>

LoadComponent(selector: string){
    // Load using selector?
}

There may be a need of exporting components in the NgModule and importing the NgModule where we want to load it.

Not sure on how to achieve this, any pointers in right direction would be very helpful.

Thanks in advance!!

like image 570
Madhu Ranjan Avatar asked Nov 20 '22 21:11

Madhu Ranjan


1 Answers

Well I was able to resolve 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 it helps someone.. !!!

like image 144
Madhu Ranjan Avatar answered Jun 04 '23 23:06

Madhu Ranjan