0

I have validated my form using reactive form validation using @rxweb package in my form and i want to show error message without multiple *ngIf I have refered a question related to it , but i could not find proper solution to my question

Here is my component.html code:

    <div [formGroup]="userForm">
      <div>
    <input type="text" formControlName="firstname"/>
        <div *ngIf="userForm.controls.firstname.errors && 
   userForm.controls.firstname.errors.required"
        class="alert alert-danger">
          This field is Required
        </div>
        <div *ngIf="userForm.controls.firstname.errors && userForm.controls.firstname.errors.maxLength"
        class="alert alert-danger">
          max length 10
        </div>

        <div *ngIf="userForm.controls.firstname.errors && userForm.controls.firstname.errors.minLength"
        class="alert alert-danger">
          minimum length is 5
        </div>
    </div> 

I dont want to write multiple *ngIf conditions Is there any other way to efficiently show reactive form config error messages ?

Avni Patel
  • 53
  • 8
  • Please goto this link : https://stackoverflow.com/questions/53920271/what-is-the-best-practice-to-show-reactive-form-error-message-without-multiple/54105704#54105704 – Ami Vyas Jan 09 '19 at 08:14

1 Answers1

0

set your all error messages in a Global variable and the property name should be same as error name

                         errorMessages = {
                           required: 'This field is Required',
                           maxLength: 'max length 10',
                           minLength: 'minimum length is 5'
                          }
                          errorMessage = '';

call the below function when you want to show error

                 showErrors() {
         this.errorMessage = '';
         var errorName = Object.keys(userForm.controls.firstname.errors);
         this.errorMessage = this.errorMessages[errorName[0]];
            } 

change your html like below

           <div [formGroup]="userForm">
           <div>
         <input type="text" formControlName="firstname"/>
        <div *ngIf="userForm.controls.firstname.errors"
         class="alert alert-danger">
        {{errorMessage}}
       </div>
     </div> 
Dharan
  • 262
  • 2
  • 14