Lekhnath
Lekhnath

Reputation: 4635

Angular2 doesnot support nested properties in form

Any way to support nested fields in Angular2.

Class

ngOnInit() {
 this.form = this._fb.group({

  name: {
    given: ['', Validators.required],
    middle: [''],
    family: ['', Validators.required]
  }

 });
}

Template

<form [ngFormModel]="form">

<input ngControl="name.given" type="text" placeholder="First Name">
<input ngControl="name.middle" type="text" placeholder="Middle Name">
<input ngControl="name.family" type="text" placeholder="Last Name">

</form>

I'm getting following Cannot find control 'name.given' error output in console. I've tried some other syntax name['given'], name[given] etc against ngControl but getting the same kind of error.

How do you work with nested fields in angular2 ?

Upvotes: 0

Views: 155

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202296

You fix inline form (with ngControl) and programmatic form with FormBuilder - in this case, you need to use ngFormControl).

I think that you're looking for form groups. Here is a sample:

<div ngControlGroup="name" #cgName="ngForm">
  <p>First: <input ngControl="give" required></p>
  <p>Middle: <input ngControl="middle"></p>
  <p>Last: <input ngControl="family" required></p>
</div>

See this plunkr: https://plnkr.co/edit/M4FGTNAx8lo8jzBivH0P?p=preview.

Upvotes: 2

Related Questions