【问题标题】:How to add dynamically FormControl in angular 6如何在角度 6 中动态添加 FormControl
【发布时间】:2018-08-31 16:47:56
【问题描述】:

我从 API 收到一组问题。每个问题都有问题 ID。 如何将问题 ID 动态绑定到 formControlName

【问题讨论】:

  • 如果您尝试过,请在此处发布,以便我们提供帮助
  • 我收到此错误 -> 错误:找不到带有路径的控件:'project_form -> 1 -> f4ca07b0-a5fe-11e8-8311-e79475dba1d1'

标签: angular angular-reactive-forms


【解决方案1】:

您可以在模板中使用 ngFor 并绑定动态 formControlName

模板:

 <form [formGroup]="formGroup">
  ...
  <ul>
    <li *ngFor="let question of questions">
      <input [formControlName]="questions.id">
    </li>
  </ul>
  ...
</form>

组件:

const questions = [{id: 1}, {id: 2}]; // just for demo
this.formGroup = this.fb.group(
  questions.reduce((acc, curr) => ({ ...acc, [curr.id]: '' }), {})
);

这将基于此对象生成 formGroup:{1: "", 2: "", 3: ""}。如果需要,还可以为表单控件设置初始值:

const questions = [{id: 1, value: 'q1'}, {id: 2, value: 'q2'}]; // just for demo
this.formGroup = this.fb.group(
  questions.reduce((acc, curr) => ({ ...acc, [curr.id]: curr.value }), {})
);

【讨论】:

  • 我以相同的方式完成了此操作,但它显示此错误我收到此错误 -> 错误:找不到带有路径的控件:'project_form -> 1 -> f4ca07b0-a5fe-11e8- 8311-e79475dba1d1 ........我不知道为什么
猜你喜欢
  • 2018-07-27
  • 2018-11-28
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 2019-04-02
  • 1970-01-01
相关资源
最近更新 更多