Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 558
Adouani Riadh Avatar asked Dec 04 '18 17:12

Adouani Riadh


2 Answers

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.

like image 104
Sachin Gupta Avatar answered Sep 24 '22 06:09

Sachin Gupta


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.

like image 41
progm Avatar answered Sep 22 '22 06:09

progm