After setting up a nested formgroup, everything seems to be working fine. However, I'm facing some challenges with properly configuring validation alerts for nested form elements.
One specific issue I encountered is an error during the build process: Property 'controls' does not exist on type 'AbstractControl'
Below is my code example:
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()
});
}
}
The challenge lies in setting up the validation with the div that has the 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>