Search code examples
angularangular-formsangular-reactive-formsangular-formbuilder

Remove validators from form control Angular 6


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..


Solution

  • 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>