Angular - 嵌套表单组中的双向绑定

时间:2018-06-08 06:43:00

标签: angular data-binding nested-forms

我使用构建器创建了一个嵌套的表单组。在数据库中添加数据是成功的,但是当我尝试将数据映射回相同的表单时,不确定如何实现它。我认为双向约束将有所帮助,但面临许多问题。任何人都可以建议如何在嵌套表单组中实现双向绑定。

ngOnInit(){

this.myForm = this._fb.group({
  name: ['', [Validators.required, Validators.minLength(5)]],
  addresses: this._fb.array([
      this.initAddress(),
  ]),
  search:['']
});
  }

  initAddress() {
return this._fb.group({
    street: ['', Validators.required],
    postcode: ['']
});
  }

  addAddress() {

const control = <FormArray>this.myForm.controls['addresses'];
control.push(this.initAddress());
  }

客户界面是:

export class Customer {
_id?: string;
name: string;
addresses: Address[];
}

export interface Address {
street: string;
postcode: string;
}

我从数据库中获取了特定数据。现在我想使用相同的组件(用于添加)进行更新。

模板是:

<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value)">

<div class="form-group">
    <label>Name</label>
    <input type="text" formControlName="name">
    <small *ngIf="!myForm.controls.name.valid" class="text-danger">
        Name is required (minimum 5 characters).
    </small>
</div>

<div formArrayName="addresses">
    <div *ngFor="let address of myForm.controls.addresses.controls; let i=index">
        <div>
            <span>{{ applicant[i] }}</span>
            <!-- <span *ngIf="myForm.controls.addresses.controls.length > 1" (click)="removeAddress(i)">
            </span> -->
        </div>
        <div [formGroupName]="i">
            <app-address [group]="myForm.controls.addresses.controls[i]"></app-address>
        </div>
    </div>
    <button type="add" (click)=" addAddress(i)">Add address</button>
</div>

<p>Form value: {{ myForm.value | json }}</p> 
<br>
<p>Form value: {{ myForm.status | json }}</p>

<button type="submit" [disabled]="!myForm.valid">Submit</button>
<button type="reset">Reset</button>

</form>

地址组件模板:

<div [formGroup]="adressForm">
<div class="form-group col-xs-6">
  <label>street</label>
  <input type="text" class="form-control" formControlName="street">
  <small [hidden]="adressForm.controls.street.valid" class="text-danger">
      Street is required
  </small>
</div>
<div class="form-group col-xs-6">
  <label>postcode</label>
  <input type="text" class="form-control" formControlName="postcode">
</div>
</div>

1 个答案:

答案 0 :(得分:2)

只需在FormGroup上调用setValue或patchValue方法,并将表单所需的值传递给它。该对象显然应该与FormGroup的结构匹配。

this.myForm.patchValue({
    name: 'some name',
    search: 'some value',
    addresses: [{
        street: 'some street',
        postcode: '11111'
    }]
})