Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 744
Jon Sud Avatar asked Nov 07 '22 06:11

Jon Sud


People also ask

What is dirty in Angular?

When the user changes the value in the watched field, the control is marked as "dirty" When the user blurs the form control element, the control is marked as "touched"

What is asynchronous validation in Angular?

Angular does not provide built-in type async Validation implmentation, it provides only for sync validation. The implementation of async validator is very similar to the sync validator. The only difference is that the async Validators must return the result of the validation as an observable or as Promise.

What is Abstractcontrol in Angular?

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.

What are the types of validator functions in Angular?

Custom Validators for template-driven forms. Comparing validation in template-driven vs reactive forms. Form-level (multi-field) Validators. Asynchronous Validators.


1 Answers

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
like image 137
Andrei Avatar answered Nov 15 '22 10:11

Andrei