In Angular 4 app I have a form model like this:
this.form = this._fb.group({
title: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]],
description: ['', [Validators.required, Validators.minLength(3)]]
});
Now what I want is to remove dynamically only the required validator from the control validators array. Something like this:
saveDraft() {
this.form.controls['title'].removeValidator('required'); //Just a fake implementation for demonstration
}
This question is not the duplicate of the mentioned question. My case is different I just want to remove the required validator unknowingly the other ones.
I don't like clearing and setting validators, as I have to repeat all static validators (patterns, min, max, etc.) just to have a dynamic "required" validator.
I use a conditional validator:
I can then mix a static validator with a dynamic "required" condition:
Where
isClientProj()
is the condition function (closure)To Add Validators:
or
this.form.get('title').setValidators([Validators.required,Validators.minLength(3), Validators.maxLength(50)]);
To Remove the 'Required' validator only, you can reset the validators.
updateValueAndValidity determines how the control propagates changes and emits events when the value and validators are changed