簡體   English   中英

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 數據?

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

有關更多詳細信息,請參閱此帖子

如果您的表單中沒有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))
});
  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 || []);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM