如何在 angular 6 中动态添加 FormControl [英] How to add dynamically FormControl in angular 6

查看:44
本文介绍了如何在 angular 6 中动态添加 FormControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了一组来自 API 的问题.每个问题都有问题 id.如何将问题 id 动态绑定到 formControlName?

I am getting a set of question from API. Each question has question id. How can I dynamically bind the question id to the formControlName?

推荐答案

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

You can use ngFor inside your template and bind dynamic 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: ""}.如果需要,您还可以为表单控件设置初始值:

This will generate formGroup based on this object: {1: "", 2: "", 3: ""}. If you want, you can also set initial values to the form controls:

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 }), {})
);

这篇关于如何在 angular 6 中动态添加 FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆