首页 > 解决方案 > 使用构造函数参数创建动态组件

问题描述

有没有办法动态创建需要构造函数参数的组件?

澄清一下:我使用 ComponentFactory 创建组件,如下所示:

const factory = this.resolver.resolveComponentFactory(MyComponent);
const componentRef: ComponentRef<MyComponent> = this.myInsertionpoint.createComponent(factory);

该组件有一个只读字段,应该通过构造函数设置。

export class MyComponent {
  private readonly _myField: MyField;

  constructor(myField: MyField) {
    this._myField = myField;
  }

...
}

我知道我可以删除只读设置字段,例如

component.instance.myField = "myValue";

...但我宁愿保持原样,因为该字段仅应在创建组件时设置。

标签: angulardynamicconstructorargumentscomponents

解决方案


推荐阅读