简体   繁体   中英

Load component dynamically in Angular 2 using selector

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

suppose your index.html has . then in your .ts or js file, when condition ready, do this: var div = document.getElementById('container');

    div.innerHTML = "<my-component></my-component>"

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

You can load any component dynamically using ComponentResolver.
Add following html node into 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);
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM