I have setup a nested formgroup. So far everything works fine. But I am not sure how to set up the validation alerts properly when there are nested form elements.
One particular thing that happens is during the build I get error: Property 'controls' does not exist on type 'AbstractControl'
Here is my code:
import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Reactive Form - Nested FormGroups';
myForm: FormGroup;
constructor(
private fb: FormBuilder
) {}
ngOnInit() {
this.buildForm();
}
buildForm() {
this.myForm = this.fb.group({
user : this.fb.group({
'firstName': new FormControl('', Validators.required),
'lastName': new FormControl('', Validators.required)
}),
'bio': new FormControl()
});
}
}
My problem is with the validation see the div with class="validation-message"
<hello name="{{ name }}"></hello>
<form [formGroup]="myForm">
<div class="my-box" formGroupName="user">
<label>
First Name
<input type="text" formControlName="firstName">
<div class="validation-message" *ngIf="!myForm.controls.user.controls['firstName'].valid && myForm.controls.user.controls['firstName'].dirty">
This field is invalid
</div>
</label>
</div>
<div class="my-box" formGroupName="user">
<label>
Last Name
<input type="text" formControlName="lastName">
</label>
</div>
<div class="my-box">
<label for="bio" class="block-me">Bio</label>
<textarea formControlName="bio"></textarea>
</div>
</form>
<p>
Data from form: {{ myForm.value | json }}
</p>