Angular2 patchValue JSON data to formArray

我是研究僧i 提交于 2020-12-29 12:00:15

问题


I have a Json data like this:

assets/details.json

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

I want to show those all JSON data in Angular forms with patchValue.

I've tried this.

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

And I've design my HTML page like this: 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>

But nothing works as I expected. Nothing can fill up to the form. I don't know how to do further.

How can I get all those JSON data in form fields?


回答1:


If you were not to have a FormArray in your form, you could just use this.data.patchValue(data) (or setValue if all properties match), but since you have a formarray, you need to iterate your address array in your object and push formgroups to your formarray. Also I see no need to initially create an empty formgroup when building the form, so I have left it out:

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



回答2:


patchValue only updates the existing FormArray, it won't modify the structure of your FormArray. You have to make sure your FormArray is of the right size before patching it, you can also recreate it completely, as shown below:

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

See this post for more details.




回答3:


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


来源:https://stackoverflow.com/questions/54426550/angular2-patchvalue-json-data-to-formarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!