Wednesday 4 September 2019

Easy Way to Highlight Invalid Fields in Submitted Angular Form

Here is one way to highlight invalid input fields after submitting a form in Angular (Template Driven Form approach) to help user quickly seeing the invalid input fields.

First we create a variable to indicate whether the form has been submitted or not:
export class PropertyPage {
    isSubmitted: boolean;

    constructor() {
        this.isSubmitted = false;
        . . .
    }
 
    addPropertyDetails(form: NgForm) {
        this.isSubmitted = true;
        . . .
        if (form.valid) {
            . . .
        }  
    }
}

Then use this variable to assign a CSS class to the form using ngClass:
<form #propertyDetailsForm="ngForm" (ngSubmit)="addPropertyDetails(propertyDetailsForm)" [ngClass]="{'submitted': isSubmitted}">
    . . .
</form>

Finally, add the style in the page stylesheet. By default, invalid input field will be assigned ng-invalid class by Angular.
.submitted input.ng-invalid {
    border: 1px solid #f00;
}

No comments: