user1593670
user1593670

Reputation: 37

clearvalidators() not working as expected along with form reset method in angular

I am trying to clear form values as well as validation messages from form on radio button change event but it still display validation message while the form control is empty

 changePaymentType(type) {
    this.myForm.reset();
    this.myForm.clearValidators();
    this.myForm.updateValueAndValidity();

form image after reset and clearvalidator

this is the output that I get after reset() and clearvalidator() method get executed.

If I execute the code in a for loop on each control it do work but then validation stop working on the form controls.

 <input type="text" class="form-control" autocomplete="off" placeholder="Card Name"
               formControlName="cardName">
        <div class="font-red" *ngIf="(f.cardName.touched || f.cardName.dirty || validateCard)  && f.cardName.errors">
          {{getValidationErrors(f.cardName.errors)}}
        </div>

Thats the html code of form control

Upvotes: 2

Views: 4406

Answers (2)

ammadkh
ammadkh

Reputation: 597

you're missing the updateValueAndValidity() function that needs to be called after updating the validators. Moreover, it is recommended to clear validators of controls instead of whole formGroup;

this.myForm.get('cardName').clearValidators();
this.myForm.get('cardName').updateValueAndValidity();

Upvotes: 4

N.F.
N.F.

Reputation: 4202

You have to execute updateValueAndValidity().

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

Upvotes: 0

Related Questions