Search code examples
angular-reactive-formsangular4-formsangular-validationangular-validator

Understanding static methods inside the Validation class in angular4


i am starting to learn model driven forms in angular and when i was going through the documentation of the model driven forms i found this

component.ts

 this.myForm= this.fb.group({
      'contact':['',Validators.required]
    }); 

now when i went to the definition of the validator class i found this

export declare class Validators {
...
static required(control: AbstractControl): ValidationErrors | null;
...
}

which explains required is a static method in the validator class and it requires a AbstractControl as a parameter. but why then i am allowed to use it without passing any parameter inside it.


Solution

  • The required method returns an error map with the 'required' property: {'required':true} if the value of control: AbstractControl is empty and null if its not.

    .

    From the angular source code: https://github.com/angular/angular/blob/6.1.9/packages/forms/src/validators.ts#L133-L154

    static required(control: AbstractControl): ValidationErrors|null {
        return isEmptyInputValue(control.value) ? {'required': true} : null;
      }
    

    .

    The reason why you can pass Validators.required without parenthesis and parameters is because Typescript is a superset of Javascript, which can store functions as variables:

    var Foo = function (control: AbstractControl)
    {
      return anyVal;
    };
    

    Is the same as:

    Foo(control: AbstractControl): any
    {
      return anyVal;
    };
    

    So doing this is completely valid

    var Bar = Foo;
    

    And because a function is just a variable holding executable code, we can store the function in multiple variables or pass it as a parameter, which is what is done in the FormControl.

    So basically, when you do

    const control = new FormControl('', Validators.required);
    

    You are not executing the required method, because a method is executed only when parenthesis and parameters are added. Instead, you are passing the Validator function itself.