I write a function that check the errors, and than i use ngIf
to display (or not) a custom text. this way:
// ts
handleError = (controlName: string, errorName: string) => {
return this.form.controls[controlName].hasError(errorName);
}
// html
<mat-error *ngIf="handleError('tipo', 'required')">Campo obbligatorio</mat-error>
It works nice for "one-level" form group. But what about nested form group? Such as:
this.form = this.fb.group({
field1: [data.field1, [Validators.required]],
myObj: this.fb.group({
field2: [data.myObj.field2, [Validators.required]],
})
});
Here it seems to crash (saying Cannot read properties of undefined (reading 'hasError') on console).
What's so the best approch to iterate any nested formgroup and check for errors?