angularangular-validationangular-validator

How do you determine which validator condition failed in angular 8


for example I have an input , and I add muti validate conditions like: required , mail and pattern , so any one failed will lead the controls.status gave me "INVALID" , what shall I do if I want to know which one is failed?


Solution

  • To display errors when using template driven forms:

    <input type="text" 
           id="name"
           required
           [(ngModel)]="model.name" 
           name="name"
           #name="ngModel">
    <div>{{name.errors | json}}</div>
    

    To display errors when using reactive forms:

    <form [formGroup]="profileForm">
      <label>
        First Name:
        <input type="text" formControlName="firstName">
      </label>
      <div>{{profileForm.get('firstName').errors | json}}</div>
    </form>
    

    I suggest to use or create some directive/component which will display errors for you.