I am using Angular with reactive forms and material UI. I have a form in which I have a text field that is only required if another field has a certain value - for example, a text input that only appears and is required if a radio button is selected. Here is an example code snippet:
<div>
Do you have any concerns?
</div>
<mat-radio-group formControlName="haveConcerns">
<mat-radio-button [value]=true>yes</mat-radio-button>
<mat-radio-button [value]=false>no</mat-radio-button>
</mat-radio-group>
<div [hidden]="!form.value.haveConcerns">
<div>
if "YES", please list the reasons:`enter code here`
</div>
<mat-form-field>
<input formControlName="concerns" matInput placeholder="reasons" type="text">
<mat-error *ngIf="hasError(this.form, 'concerns', 'maybeRequired')">
please explain any concerns your may have
</mat-error>
</mat-form-field>
</div>
My issue is that the validation is called when the form is first drawn, and it passes because the button is not checked. But when the user clicks the radio button, the field will not re-run its validation since it was not changed.
Right now I am manually setting the value of the concerns field to itself in order to make the validation re-run but it feels like a hack.
public applyForm(formValue) {
this.formIsSubmitted = true;
const concernsField= this.form.get('concerns');
concernsField.setValue(concernsField.value);
if (this.form.valid) {
this.submitFormValue(formValue);
}
}
Is there a better way? If I have a large form, this gets unwieldy. I saw that there is a setDirty method but I tried it on both the form and the control and it didn't appear to do anything.