angular - 如何在angular2中使用组件名称动态加载组件?

标签 angular

我目前正在使用以下代码在我的应用程序中动态加载 Angular 组件。

export class WizardTabContentContainer {
  @ViewChild('target', { read: ViewContainerRef }) target: any;
  @Input() TabContent: any | string;
  cmpRef: ComponentRef<any>;
  private isViewInitialized: boolean = false;

  constructor(private componentFactoryResolver: ComponentFactoryResolver,   private compiler: Compiler) {
  }

  updateComponent() {
     if (!this.isViewInitialized) {
       return;
     }
     if (this.cmpRef) {
       this.cmpRef.destroy();
     }
     let factory = this.componentFactoryResolver.resolveComponentFactory(this.TabContent);

     this.cmpRef = this.target.createComponent(factory);
   }
}

这里 resolveComponentFactory 函数接受组件类型。我的问题是,有什么方法可以使用组件名称字符串加载组件,例如我将组件定义为

export class MyComponent{
}

如何使用组件名称字符串“MyComponent”而不是类型添加上述组件?

最佳答案

也许这会奏效

import { Type } from '@angular/core';

@Input() comp: string;
...
const factories = Array.from(this.resolver['_factories'].keys());
const factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);

其中 this.comp 是您的组件的字符串名称,例如 "MyComponent"

Plunker Example

要做到这一点,请参阅缩小

关于angular - 如何在angular2中使用组件名称动态加载组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40115072/

相关文章:

typescript - 如何从父组件提交表单?

angular - 除了 app.component 的 ngOninit 之外,在哪里放置 api 调用以使系统等待响应返回并注入(inject)到主体中?

javascript - TypeScript 中的 findIndex 数组方法

javascript - 未捕获( promise ): TypeError: Cannot read property 'component' of null

node.js - WEBPACK 弃用数组以使用 web pack 5 在 angular 11 中设置警告

angular - 如何更改 Angular 5 Material 输入占位符?

angular - primeng table p-table 列和浏览器窗口大小调整时的数据重叠问题

angular - 从 Angular 8 通用版迁移到 9 通用版失败 : require. 解析不是函数

OOP/Typescript - 当类构造函数将接口(interface)对象作为参数时,是否可以优化代码?

Angular - 在 Azure 上托管时,在运行时从服务器变量读取配置