Angular2 patchValue JSON 数据到 formArray

Angular2 patchValue JSON data to formArray

我有一个这样的 Json 数据:

assets/details.json

{
    "name" : "john",
    "age"  : 20,
    "address" : [{
        "main": "address1",
        "sub": "address2"
    },
    {
        "main": "add1",
        "sub": "add2"
    }]
}

我想用 patchValue 以 Angular 形式显示所有 JSON 数据。

我已经试过了。

app.component.ts

export class AppComponent {
  data: FormGroup

  constructor(private FB: FormBuilder, private service: DataService) { }

  ngOnInit() {
    this.data = this.FB.group({
      name: [''],
      age: [''],
      address: this.FB.array([
        this.addAddress()
      ])
    })

    this.getData()

  }

  addAddress(): FormGroup {
    return this.FB.group({
      main: [''],
      sub: [''],
    })
  }

  getData() {
    this.service.getData('../assets/details.json').subscribe((data) => {
      this.data.patchValue({ data })
    }
}

我的 HTML 页面设计如下: app.component.html

<form [formGroup]="data" (ngSubmit)="onSubmit()">
  <input formControlName="name" type="text" class="form-control col-sm-8">
  <input formControlName="age" type="number" class="form-control col-sm-8">

  <div formArrayName="address" *ngFor="let d of data.get('address').controls; let i = index;">
    <div [formGroupName]="i">
      <input formControlName="main" type="text" class="form-control">
      <input formControlName="sub" type="text" class="form-control" />
    </div>
  </div>
</form>

但没有任何效果如我所料。没有什么可以填写表格。我不知道该怎么做。

如何在表单字段中获取所有这些 JSON 数据?

如果您的表单中没有 FormArray,您可以只使用 this.data.patchValue(data)(如果所有属性都匹配,则可以使用 setValue),但是由于您有一个 formarray,您需要在对象中迭代 address 数组并将表单组推送到表单数组。此外,我认为在构建表单时不需要最初创建一个空的表单组,因此我将其省略:

ngOnInit() {
  this.data = this.FB.group({
    name: [''],
    age: [''],
    address: this.FB.array([])
  })
}

get formArr() {
  return this.data.get('address') as FormArray;
}

// ....
this.data.patchValue({name: data.name, age: data.age});
data.address.forEach((x) => {
  this.formArr.push(this.FB.group(x))
});

patchValue 只会更新现有的 FormArray,不会修改您的 FormArray 的结构。打补丁之前一定要确保你的FormArray大小合适,你也可以完全重新创建,如下图:

this.data.patchValue({ name: data.name, age: data.age });

this.data.controls['address'] = this.FB.array(data.map(address => {
    const group = this.addAddress();
    group.patchValue(address);
    return group ;
}));

看到这个

  this.formCustomer.patchValue({ ...response.data })
   response.data.contactos.forEach(c => {
     this.contactos.push(this.Contact(c))
    });
      
get contactos(): FormArray {
  return <FormArray>this.formCustomer.get("contactos")
      }

Contact(item?:any): FormGroup {
        return this.fb.group({
          tipo: [item?item.tipo:'', [Validators.required]],
          nombre: [item?item.nombre:'', [Validators.required]],
          tel: [item?item.tel:'', [Validators.required]],
          tel_2: [item?item.tel_2:''],
        })
      }
this.formCustomer = this.fb.group({
    contactos: this.fb.array([this.Contact()]),
    })

getData() 方法的工作原理如下:

getData() {
    this.service.getData('../assets/details.json').subscribe((_data) => {
      this.data.patchValue(data)
      (this.data as FormGroup).setControl('address', this.fb.array(this.data.address || []);
    }
}