liveBook · Manning

Controls property

As explained in Pro Angular 16

The controls property of an Angular form controller exposes an object containing the individual controls in the form.

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

How Pro Angular 16 covers it

How deep it goes
Defines the returned object and demonstrates Object.keys iteration, but stops short of explaining Angular’s internal control implementation.
Examples
Uses a product form, a name control, getMessages, and an overall validation-error list.
What it assumes
Assumes familiarity with NgForm, individual template controls, and validation errors.
What you can do after
Diagnose form-wide validation failures by enumerating controls and collecting their error messages.
How it connects
Connects NgForm, NgModel, validation errors, and form submission.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.