Alexandre Justino
Alexandre Justino

Reputation: 1726

Nested attributes in FormBuilder

I'd like to know if there's a way to set nested attributes using Angular 2's FormBuilder, something like this:

this.form = formBuilder.group({
  name: ['', Validators.required],
  email: ['', Validators.required],

  address: {
     state: ['ca', Validators.required],   // <---- this gives an error
  }
});

Template:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <ion-item-divider color="light">Personal Data</ion-item-divider>
  <ion-item>
    <ion-label floating>Name</ion-label>
    <ion-input type="text" formControlName="name"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label floating>Email</ion-label>
    <ion-input type="text" formControlName="email"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label floating>State</ion-label>
    <ion-input type="text" formControlName="address.state"></ion-input>
  </ion-item>
</form>

This gives me an error saying that it couldn't find an field name state, even though it is there.

This would help me a lot, because I have a very long form and it would be good to organize it better.

Thanks in advance.

Upvotes: 2

Views: 617

Answers (2)

silentsod
silentsod

Reputation: 8335

Sasxa was halfway in his answer but missed that you were seeing the error in the template evaluation portion. Hence why posting the template was important.

To fix it you wrap your address portion of the template in some unobtrusive element like:

<span formGroupName="address">
    <ion-item>
        <ion-label floating>State</ion-label>
        <ion-input type="text" formControlName="state"></ion-input>
     </ion-item>
</span>

and when you're building the form do as was suggested:

address: formBuilder.group({
   state: ['ca', Validators.required]
})

Doc for FormGroupName

Upvotes: 4

Sasxa
Sasxa

Reputation: 41294

Try this:

this.form = formBuilder.group({
  name: ['', Validators.required],
  email: ['', Validators.required],

  address: formBuilder.group({
     state: ['ca', Validators.required],
  }),
});

and in template:

<ion-input type="text" [formControl]="address.get('state')"></ion-input>

Upvotes: 2

Related Questions