0
votes

In angular js, we have $submitted to populate error messages on submit click.

How can we display all validation errors on submit click in Angular

HTML:

<form #nameForm="ngForm" novalidate (ngSubmit)="saveNameForm(formModel)">
<div class="form-group">
   <label for="inputName" class="form-control-label"> Name</label>
   <input type="text" id="inputName" name="lotCode [(ngModel)]="formModel.name" #lotCode="ngModel" aria-describedby="nameHelp"
     autocomplete="new-password" required>
   <small id="nameHelp" class="text-danger" *ngIf="lotCode.invalid && lotCode.touched">Required</small>
</div>

<div class="form-group">
    <label for="inputDescription" class="form-control-label"> Description</label>
    <input type="text" id="inputDescription" name="desCode" [(ngModel)]="formModel.description" #desCode="ngModel" aria-describedby="descriptionHelp"
     autocomplete="new-password" required>
    <small id="descriptionHelp" class="text-danger" *ngIf="desCode.invalid && desCode.touched">Required</small>
</div>

<button type="submit">Submit </button>
</form>

Component:

 export class AppComponent  {
 formModel: FormModel= new FormModel();
 saveNameForm(formModel){
 console.log(formModel)
 }
 }
 export class FormModel {
 name: string;
 description:string;
 }

https://stackblitz.com/edit/angular-rizsuy?file=src%2Fapp%2Fapp.component.ts

2

2 Answers

0
votes

Angular uses the same form validation that native HTML5 does. Just do this in an Angular context. In the following example, we can use *ngIf to control the display of the messages, and .dirty and .touched to determine if the user interacted with the input.

Example from docs:

<input id="name" name="name" class="form-control"
  required minlength="4" appForbiddenName="bob"
  [(ngModel)]="hero.name" #name="ngModel" >

  <div *ngIf="name.invalid && (name.dirty || name.touched)"
  class="alert alert-danger">

  <div *ngIf="name.errors.required">
    Name is required.
  </div>
  <div *ngIf="name.errors.minlength">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors.forbiddenName">
    Name cannot be Bob.
  </div>
</div>
0
votes

Here is the solution: https://stackblitz.com/edit/angular-8jaaqz?file=src%2Fapp%2Fapp.component.html

You should use a variable to set submitted if submitted then will display error