angularangular-reactive-formsangular2-formsangular2-form-validation

How Remove custom Validators with method RemoveValidators


I have a question how can I remove my custom validators in the easiest/best way? I know that since angular 12 there is a method RemoveValidators, it is based on the reference of a given validator, that is, it is not easy to remove it.

What is the best way to remove such validators with parameters ?

Below i added stackblitz with non working sample: https://stackblitz.com/edit/base-angular-12-app-arm6g6?file=src/app/app.component.ts


Solution

  • The reason your code fails is because you are incorrectly passing the reference to your method.

    Every time you call AppComponent.forbiddenNameValidator(/admin|test|abc/) you return a new anonymous function.

    In your code, you are calling it twice, first in line 25 and then in line 37. Each of the calls generates a new anonymous function which has its own reference. You can prove this by simply doing the following test:

    const first = AppComponent.forbiddenNameValidator(/admin|test|abc/);
    const second = AppComponent.forbiddenNameValidator(/admin|test|abc/);
    
    console.log(first === second) // false
    

    Then, how do we fix this?

    According to the Official Documentation, you need to store the return value of the validator in a const or property.

    This stackblitz contains a link with this approach. Notice that the return of the validator is being stored in a property:

    forbiddenNameValidator = ForbiddenNameValidator(/admin|test|abc/);f
    

    This property is then passed in validators array and in the removeValidators method. Also note that I added the call to the updateValueAndValidity() of the form after removing the validator.

    This is because according to the documentation, you should always call the updateValueAndValidity() of the form whose validators where altered.