I have been developing an e-commerce app with Angular 14 and Angular Material.
I run into a problem while tiring to display specific (custom) validation messages for some of the fields of the registration form.
In the form component's Typescript file, I have:
import { FormService } from '../../services/form.service';
export class FormComponent implements OnInit {
constructor (
private formService: FormService
) { }
public form: FormGroup = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
workInfo: new FormGroup({
companyName: new FormControl('', Validators.required),
companyCity: new FormControl('', Validators.required),
}),
});
ngOnInit(): void {
}
}
In the template:
<form [formGroup]="form" novalidate>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>First name:</mat-label>
<input matInput formControlName="firstName">
<mat-error *ngIf="form.controls['firstName'].errors?.['required']">What's your first name?</mat-error>
</mat-form-field>
<div formGroupName="workInfo">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Company name:</mat-label>
<input matInput formControlName="companyName">
<mat-error *ngIf="form.controls['companyName'].errors?.['required']">What company do you work for?</mat-error>
</mat-form-field>
</div>
</form>
Using this syntax also does not work:
<mat-error *ngIf="form.controls['workInfo.companyName'].errors?.['required']">What company do you work for?</mat-error>
The problem
Although I can display specific validation messages for the firstName
field (or any other that isn't enclosed in a form group), I can not do the same for any of the fields inside the <div formGroupName="workInfo">
element.
I get an TypeError: Cannot read properties of undefined (reading 'errors')
for any pf them.
Questions
- What am I doing wrong?
- What is the easiest and most reliable way to achieve the desired result?
CodePudding user response:
I believe since your form group attributes are public, you can just use this syntax when validating, to me, that looks like the only issue.
<mat-error *ngIf="form.get('workInfo.companyName')?.errors?.required">What company do you work for?</mat-error>