0

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 ?

1
  • And here is the answer. Commented Jun 13, 2016 at 8:23

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Now I am getting Cannot find control 'name -> given' error message in console.
Perhaps you forgot the form element. I added a plunkr in my answer ;-)
Its not working with [ngFormModel] here
Yes it's normal because you can't mix inline forms with ones defined with FormBuilder... Note that you can define groups with FormBuilder as well. Here is a sample: angular.io/docs/ts/latest/api/common/index/….
@ThierryTemplier, can you update your answer to rc5 requirements?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.