动态地将动态创建的组件分配给formGroup

时间:2019-10-23 11:13:06

标签: angular dynamic-controls reactive-forms dynamic-forms

试图基于配置文件创建动态表单。

成分是:

  • 自定义表单控件(ControlValueAccessor实现)
  • ComponentFactoryResolver
  • ReactiveFormsModule

app.component.html

<form [formGroup]="form" (ngSubmit)="submit()">
  <my-custom-input formControlName="x"></my-custom-input> <!-- working example -->
  <ng-container #container></ng-container>
  <button type="submit">Submit</button>
</form>
在解析来自配置文件formGroup的输入后,

{a: null, b: null, x: null}x是手动的,ab是动态的。

app.component.ts

createComponent(config: FormControlConfig) {
  const factory = this.resolver.resolveComponentFactory(components[config.type]);
  const componentRef = this.container.createComponent(factory);
  componentRef.instance.config = config;

  // below is the current attempt. thought to mimic the attributes as they appear in the DOM. 
  this.renderer.setAttribute(componentRef.location.nativeElement, 'formControlName', config.name);
  this.renderer.setAttribute(componentRef.location.nativeElement, 'ng-reflect-name', config.name);
  // which is a no-go.
}

当然,用任何东西填充值之后,我得到的是

{a: null, b: null, x: 'whatever'};

我还阅读了this article,其中似乎涵盖了问题e2e。但是,每个输入都需要一个包装器组件。

我希望有一个更苗条的解决方案。

如果需要,我很乐意提供更多代码

0 个答案:

没有答案