rx1984
rx1984

Reputation: 1222

Angular Validator function called multiple times

I am using Reactive form in project and I have this strange behaviour about form group validator. I made a sample example to show you the problem

export class AppComponent {
  detailsForm: any;
  constructor(private formBuilder: FormBuilder) {
    this.detailsForm = this.formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required]
    }, { validator: [this.ValidForm] });
  }
  ValidForm = (formGroup: AbstractControl) => {
    console.log('hello');
  }
}

<form [formGroup]="detailsForm" action="" id="maforme">
  <input type="text" formControlName="firstName">
  <input type="text" formControlName="lastName">
  <button type="button">Save</button>
</form>

The output is

hello app.component.ts:18
hello app.component.ts:18
hello app.component.ts:18
hello app.component.ts:18

My question why the validator was called 4 times in this case?

Upvotes: 11

Views: 6034

Answers (3)

progm
progm

Reputation: 2858

I used your example and found that when the application loads, the validator is called for:

  • FormGroup in control
  • FormGroup in html
  • FormControl in html
  • FormControl in html

You can reproduce this by commenting out the entire html with the form, and then returning it in parts and see the result in the process.

I think this is wrong behavior, but Angular works this way. I tested with version 7.1.0.

Upvotes: 3

Sachin Gupta
Sachin Gupta

Reputation: 5321

The validator is running every time the control in rendered on the UI and once when it is applied as a validator on the formGroup. You can verify this by removing the controls on UI.

Upvotes: 3

Gaurav
Gaurav

Reputation: 623

I think , you need to replace AbstractControl with FormGroup in this line - ValidForm = (formGroup: AbstractControl).

Upvotes: -2

Related Questions