使用选择器在Angular 2中动态加载组件 [英] Load component dynamically in Angular 2 using selector

查看:90
本文介绍了使用选择器在Angular 2中动态加载组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用选择器在Angular 2中动态加载组件吗?

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{
 }

我们可以使用选择器my-component

<div #container ></div>

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

可能需要在NgModule中导出组件并将NgModule导入我们要加载的位置.

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.

提前谢谢!!

推荐答案

我可以使用以下方法解决此问题,

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

这篇关于使用选择器在Angular 2中动态加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆