0

In angular I created hasError function to cover all validation cases in my component. when i tried to use it in html i found that it entered in loop more times and after that it fires validation.

I need to know why this loop accured.

my typescript function

  hasError(input) {
    if (input == "email") {
      if (this.loginForm.controls['email'].hasError('required')) return 'Validation.emailRequired';
      if (this.loginForm.controls['email'].hasError('email')) return 'Validation.invalidEmail';

      else return '';
    }
    if (input == "password") {
      if (this.loginForm.controls['password'].hasError('required')) return 'Validation.passwordRequired';

      else return '';
    }
  }

my HTML

        <mat-form-field>
          <i class="far fa-envelope"></i>
          <input matInput [placeholder]="'Login.Email'|translate"  formControlName ="email">
          <mat-error *ngIf="!loginForm.controls['email'].valid">
              {{hasError('email')|translate}} // i'm using it here 

          </mat-error>
        </mat-form-field>
Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45
fatmaaGomaa
  • 257
  • 1
  • 2
  • 7
  • 3
    Its not a loop, your app has to update view, for that it runs change detections, (on browser events, like click, input, etc. Timers, Ajax calls) to check updates in the view bindings. When those happen your `hasError()` will run – Ashish Ranjan Jun 20 '19 at 09:56
  • 1
    What? The counter will increase every time this method is called – Avin Kavish Jun 20 '19 at 10:00

0 Answers0