在FormBuilder中使用嵌套对象

时间:2017-06-01 12:01:53

标签: forms angular angular2-formbuilder

所以我有这个表单,它工作正常..但现在我想扩展一些json结构......

https://plnkr.co/edit/aYaYTBRHekHzyS0M7HDM?p=preview

我想要使用的新结构如下所示 (只有地址:已更改)

  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(5)]],
  address: this.fb.array([{
    name: '',
    addressLine1: ['', [Validators.required]],
    city: ['', [Validators.required]],
    postalCode: [Validators.required],
  }]),

但我一直收到错误,例如“ERROR TypeError:control.registerOnChange不是函数”。想通知这与formControlName缺失有关,但我不希望所有数据都显示..

在输入字段中,我只想显示addressLine1(根本不显示name,city或postalCode)。

1 个答案:

答案 0 :(得分:9)

我会使用表单组而不是for address的formarray,所以它看起来像这样:

this.registrationForm = fb.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(5)]],
  address: this.fb.group({ // make a nested group
    name: '',
    addressLine1: ['', [Validators.required]],
    city: ['', [Validators.required]],
    postalCode: [Validators.required],
  }),
});

然后在您的模板中,请记住标记formGroupName

<md-input-container formGroupName="address"> <!-- Mark the nested formgroup name -->
   <input mdInput type="text" placeholder="AddressLine1" name="address" 
         formControlName="addressLine1" fodiGoogleplace 
         (updateAdress)="setAdressOnChange($event)">
</md-input-container>

您的分叉 PLUNKER