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
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:
Then, how do we fix this?
According to the Official Documentation, you need to store the return value of the validator in a
constorproperty.This stackblitz contains a link with this approach. Notice that the return of the validator is being stored in a property:
This property is then passed in validators array and in the
removeValidatorsmethod. Also note that I added the call to theupdateValueAndValidity()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.