The controls property on an NgForm exposes an object whose properties represent the form’s individual controls. Each control provides validation state and errors comparable to an individual NgModel control. section 13.4.3
Collecting errors for the whole form
getFormValidationMessages(form: NgForm): string[] { const messages: string[] = []; Object.keys(form.controls).forEach(key => { this.getMessages(form.controls[key].errors, key) .forEach(message => messages.push(message)); }); return messages; } Call the method from a submitted form’s validation summary to display each control’s errors together at the top of the form. section 13.4.3
Listing 13.22. Validation messages in the component.ts file in the src/app folder
import { Component, computed, signal } from "@angular/core";
import { Model } from "./repository.model";
import { Product } from "./product.model";
import { NgModel, ValidationErrors, NgForm } from "@angular/forms";
@Component({
selector: "app",
templateUrl: "template.html"
})
export class ProductComponent {
private model: Model = new Model();
// ...statements omitted for brevity...
getFormValidationMessages(form: NgForm): string[] {
let messages: string[] = [];
Object.keys(form.controls).forEach(k => {
this.getMessages(form.controls[k].errors, k)
.forEach(m => messages.push(m));
});
return messages;
}
}
Browse the complete component method that enumerates form.controls and builds validation messages. section 13.4.3
