angular - 使用选择器在 Angular 2 中动态加载组件

标签 angular

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

假设我们有一个如下所示的组件,

 @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。

不确定如何实现这一点,任何正确方向的指示都会非常有帮助。

提前致谢!!

最佳答案

好吧,我能够使用下面的方法解决这个问题,

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;                    
    }
  });
}

希望对某人有所帮助..!!!

关于angular - 使用选择器在 Angular 2 中动态加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39020164/

相关文章:

javascript - 从下拉菜单中删除拼接项目

javascript - Angular 4 vs React 性能——理论与现实

angular - Tslint 无法在使用 Angular 的 Emacs 中工作

angular - 如何使用 p-listbox 过滤多个标签?

javascript - 如何在 npm 包中为 Angular 项目创建组件

angular - 为什么节目无法读取未定义的属性?

unit-testing - Angular2(2.1.0)服务中的UnitTest Mock Http响应

html - 加载数据后如何将表头与表体对齐

css - 如何在 variables.scss 中导入颜色

dart - pub serve 找不到 lib 下的文件