以下是一个示例代码,展示如何使用Angular 5从JSON结果构建表单数组。
首先,我们需要创建一个包含表单数组的FormGroup对象。在组件的ts文件中,我们导入必要的模块和类:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
然后,我们在组件类中定义一个表单组:
@Component({
  selector: 'app-form-array-example',
  templateUrl: './form-array-example.component.html',
  styleUrls: ['./form-array-example.component.css']
})
export class FormArrayExampleComponent implements OnInit {
  form: FormGroup;
  constructor(private fb: FormBuilder) { }
  ngOnInit() {
    this.form = this.fb.group({
      items: this.fb.array([])
    });
  }
}
接下来,我们创建一个方法来从JSON结果构建表单数组。假设我们有一个名为results的JSON数组,每个元素都有name和value属性。我们可以使用FormArray类的push方法将每个元素添加到表单数组中:
buildFormArrayFromResults(results: any[]) {
  const formArray = this.form.get('items') as FormArray;
  results.forEach(result => {
    formArray.push(this.fb.group({
      name: [result.name],
      value: [result.value]
    }));
  });
}
在组件的HTML模板中,我们可以使用formArrayName指令和*ngFor指令来循环遍历表单数组并显示每个元素的输入字段:
最后,在组件的ngOnInit方法中调用buildFormArrayFromResults方法,并传递一个JSON结果数组:
ngOnInit() {
  this.form = this.fb.group({
    items: this.fb.array([])
  });
  const results = [
    { name: 'Item 1', value: 'Value 1' },
    { name: 'Item 2', value: 'Value 2' },
    { name: 'Item 3', value: 'Value 3' }
  ];
  this.buildFormArrayFromResults(results);
}
现在,当组件初始化时,表单数组将根据JSON结果动态构建,并且可以在HTML模板中显示和编辑每个元素的值。
希望这个示例能帮助到你!