简体   繁体   中英

clearvalidators not working in angular 6 form control

I have two form group names like below. Sometimes one form is not shown to user. When both are shown I have no issues. And I have a button which is visible when the form is valid.

 <div
        *ngIf="showPersonalInfo"
        class="personalInfo"
        formGroupName="personalInfo"
      > 

 <div
        *ngIf="showFamilyInfo"
        class="familyInfo"
        formGroupName="familyInfo"
      > 

 <button
        *ngIf="InfoForm.valid"
        class="submitButton"
</button>

And I initialize my form using below code.

this.InfoForm = this.formBuilder.group({
  personalInfo: this.getPersonalInfo(),
  familyInfo: this.getFamilyInfo(),
});

The code in this.getFamilyInfo() will set showFamilyInfo to true or false and it initializes the form in both the cases otherwise my html throws familyInfo is not found.

One of our service sometimes looks for the member profile and pulls existing family info/personal info and fills the model and sets showPersonalInfo/showFamilyInfo to true.

when showFamilyInfo is false my InfoForm.FamilyInfo form control is showing as invalid. To avoid this error i am clearring validators using below code but it still shows the familyInfo form control status invalid. My PersonalInfo is valid though.

How can ignore everything related to FmilyInfo when showFamilyInfo is false so the button will be visible.

this.InfoForm.get('familyInfo').clearValidators();
this.InfoForm.get('familyInfo').updateValueAndValidity();

I think you need to clear the errors before you can update the Validity. In the linked post, the answer by Julia P. covers how to clear the errors. Then you run updateValueandValidity. How can I manually set an Angular form field as invalid?

I had the same issue, in my case, the code setErrors(null) solved the problem. Try to do this:

this.InfoForm.get('familyInfo').clearValidators();
this.InfoForm.get('familyInfo').setErrors(null); 
this.InfoForm.get('familyInfo').updateValueAndValidity();

setErrors(null) did the trick for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM