raju
raju

Reputation: 6936

reactive form .reset() not clearing the validators

I am using a simple reactive form in Angular6.

this.phoneForm = this._formBuilder.group({
  oldMac: new FormControl('', Validators.compose([
    Validators.required,
    Validators.pattern('')
  ])),
  newMac: ['', Validators.required],
  newModel: ['', [Validators.required]],
  targetCluster: ['', [Validators.required]],
  ownerUser: ['', [Validators.required]]
}, { updateOn: 'blur' });

To reset I am using this.phoneForm.reset();, it is clearing the form but does not clear the validators, my form is showing as invalid.

Please help

EDIT: I forget to add that I am using angular-material input.

Upvotes: 1

Views: 2098

Answers (2)

Ish
Ish

Reputation: 71

This issue is related to: https://github.com/angular/material2/issues/4190 Reset simply clears the content of the form triggering the validation to fail as no values are provided. In order to essentialy reset to a base state the forms should be marked as pristine or untouched.

    Object.keys(this.form.controls).forEach(key => {
      let control = this.form.controls[key];
      control.reset(); // clear control's contents.

      // resets the control the before user interaction state
      control.markAsPristine(); 

      // As raju stated this will not only remove errors but also remove all validators.
      control.setErrors(null); 
    });

Upvotes: 0

Peter Haddad
Peter Haddad

Reputation: 80914

You need to use the following:

this.phoneForm.clearValidators();
this.phoneForm.updateValueAndValidity();  
this.phoneForm.reset();

From the docs:

clearValidators()

Empties out the sync validator list.

updateValueAndValidity()

Recalculates the value and validation status of the control.

Upvotes: 1

Related Questions