I have a form with a lot of form controls and Validators for some of the controls, like:
title = new FormControl("", Validators.compose([
Validators.required
]));
description = new FormControl("", [
Validators.required,
Validators.minLength(1),
Validators.maxLength(2000)
]);
How do I add a save as draft button that does not validate the controls? Or remove them?
I have tried a lot of examples such as:
saveDraft() {
this.addProjectForm.controls.title.clearValidators();
this.addProjectForm.controls.title.setErrors(null);
this.addProjectForm.controls.title.setValidators(null);
}
or
saveDraft() {
this.addProjectForm.controls['title'].clearValidators();
this.addProjectForm.controls['title'].setErrors(null);
this.addProjectForm.controls['title'].setValidators(null);
}
but nothing works..
Try this:
this.addProjectForm.get('title').setValidators([]); // or clearValidators()
this.addProjectForm.get('title').updateValueAndValidity();
If you want to add a validator then append array of validators:
this.addProjectForm.get('title').setValidators([Validators.required]);
this.addProjectForm.get('title').updateValueAndValidity();
Note: You have to use updateValueAndValidity() after each change