Angular2 patchValue JSON数据到formArray

时间:2019-01-29 17:29:33

标签: angular formarray

我有一个像这样的Json数据:

assets/details.json

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

我想用patchValue以角度形式显示所有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数据?

感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

如果您的表单中没有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))
});

答案 1 :(得分:0)

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

请参阅此post for more details

答案 2 :(得分:0)

  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()]),
    })

答案 3 :(得分:-1)

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 || []);
    }
}