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
You can try following as another solution if you want to remove validator from your field:
public saveDraft(): void {
this.addProjectForm.get('title').clearValidators();
this.addProjectForm.get('title').updateValueAndValidity();
}
I have tried all of above, But for me following code has worked.
let formControl : FormControl = this.formGroup.get("mouldVendor") as FormControl;
formControl.clearValidators();
formControl.setValidators(null);
formControl.updateValueAndValidity();
I have implemented quite a lot of forms with this Save As Draft functionality.
What I generally do is, just keep the Submit Button as disabled unless the form is valid
. But keep the Save as a Draft button as always enabled.
What this allows me to do is, save the contents of the form without applying any validation in case the user clicks the Save as Draft button.
The user can not click the Save button anyway as the form is not valid.
All of this translates to code like this:
<div class="image-flip">
<div class="mainflip">
<div class="frontside">
<div class="card">
<div class="card-body add-generic-card">
<form [formGroup]="addGameForm">
...
<div class="draft-publish-button">
<button
class="..."
type="button"
(click)="onFormSubmit('DRAFT')">
Save as Draft
</button>
<button
class="..."
type="button"
(click)="onFormSubmit('PUBLISHED')"
[disabled]="addGameForm.invalid">
Publish
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With