【问题标题】:Dynamically create multiple forms in angular2在angular2中动态创建多个表单
【发布时间】:2017-11-28 21:19:44
【问题描述】:

我正在从数据库中获取一些数据,并根据我想要创建表单的结果数量。例如。如果我总共得到 3 行,其中列有 name、age 和 class 。然后我需要创建三个表单元素,名称、年龄和类别作为表单元素。在此先感谢

【问题讨论】:

    标签: angular2-template angular2-forms angular2-services angular2-directives


    【解决方案1】:

    您可以使用 FormArray 创建多个表单组。

    使用 FormBuilder,我们可以为 FormControls 创建一个 FormGroup。在 FormGroup 中定义一个变量为 FormArray 并将 FormControls 动态添加到该数组中。

    public dataForm = FormGroup;
    const dbData = // data from database eg. [{name:x, age: 8, class: A},..]
    ...
    constructor(
        private _fb: FormBuilder
    ) {}
    ...
    ngOnInit() {
        this.dataForm = this._fb.group({
           subFormList: this._fb.array([])
        });
        this.getValues();
    }
    getValues() {
       const control = <FormArray> this.dataForm.get('subFormList');
       for (row of this.dbData) {
          const temp = this._fb.group({
             name: [row['name']],
             age: [row['age']],
             class: [row['class']]
          });
          control.push(temp);
       }
    }
    

    希望这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      相关资源
      最近更新 更多