Jon Sud
Jon Sud

Reputation: 11671

Angular calls a validation function for many times

I have angular form.

When I open the app, the console is log in fooValidation four times without me don't nothing.

in fooValidation
in fooValidation
in fooValidation
in fooValidation

Why? This is it by design? how to make it execute only after the form is submit or when focus on the specified field?

import { Component } from "@angular/core";
import { FormGroup, FormControl } from '@angular/forms';

const fooValidation = () => {
  console.log('in fooValidation ');

  // check two fields here
  return { error: true };
}

@Component({
  selector: "my-app",
  template: `
      <form [formGroup]="profileForm">
    
        <label>
          First Name:
          <input type="text" formControlName="firstName">
        </label>
  
        <label>
          Last Name:
          <input type="text" formControlName="lastName">
        </label>
  
      </form>
    `
})
export class AppComponent {
  name = "Angular";

  profileForm = new FormGroup({
    firstName: new FormControl(""),
    lastName: new FormControl("")
  }, {
    validators: [fooValidation]
  });
}

stackblitz example

Upvotes: 6

Views: 1279

Answers (2)

keygjones
keygjones

Reputation: 79

I had the same problem, seemed to solve it by adding the group validators on the ngAfterViewChecked lifecycle hook.

public ngAfterViewChecked(): void {
   myFormGroup.setValidators([validator1(), validator2()])
}

Upvotes: 1

Andrei
Andrei

Reputation: 12206

it is expected. validation are expected to be pretty simple, so it is usually not a problem. now why there are 4 of them:

  1. creation of FormGroup in typescript. it is created and should be checked to define if it is in error state
  2. [formGroup] directive registers control and calls validation again, because there are some situation where something can change (not sure which exactly, but probably some issues caused that behavior to make everything right)
  3. and 4. formControlName directive does exactly the same

Upvotes: 3

Related Questions