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();
Angular tells you that it's better for you to use the ways it gives you to disable/enable form controls. You can enable/disable a form control by using the following ways: Instantiate a new FormControl with the disabled property set to true. FormControl({value: '', disabled: true}) .
We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.
Dynamically Add Validators We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.
We can either use clearValidators() to remove all validators and then use setValidators() to set needed validation, or we can directly use setValidators() with the needed validators only (without the validator you don't want to have).
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?
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