【问题标题】:Dynamic component generation in Angular 9 with constructor parametersAngular 9 中使用构造函数参数生成动态组件
【发布时间】:2020-10-04 09:00:10
【问题描述】:

下面是组件生成代码。问题是我找不到如何将值传递给构造函数的解决方案。

原码:https://stackblitz.com/edit/angular-ivy-tcejuo

private addComponent(template: string) {
    class TemplateComponent {

      @ViewChild('target', {static: false, read: ViewContainerRef}) public target;

      constructor() {
      }

      public myMethod() {
        // do something     
      }
    }

    class TemplateModule {
      @ViewChild('target', {static: false, read: ViewContainerRef}) public target;
    }

    const componentType = Component({template: template + '<div #target></div>'})(TemplateComponent)

    const componentModuleType = NgModule({declarations: [componentType]})(TemplateModule)

    const mod = this.compiler.compileModuleAndAllComponentsSync(componentModuleType);
    const factory = mod.componentFactories.find((comp) =>
        comp.componentType === componentType
    );
    this.container.createComponent(factory);
  }

如果您在模板组件类中编辑构造函数参数(例如私有渲染:Renderer2),则会开始生成错误:

此构造函数与 Angular 依赖注入不兼容 因为它在参数列表索引 0 处的依赖无效。

请帮助解决这个问题。

【问题讨论】:

    标签: javascript angular typescript web components


    【解决方案1】:

    你需要从 @angular/core 导入 Renderer2

    import { Component, VERSION, ViewChild, ViewContainerRef, NgModule, Compiler, AfterViewInit ,Renderer2} from '@angular/core'

    【讨论】:

    • 这个解决方案对我不起作用,因为我正在导入组件并且错误仍然存​​在。
    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多