Angular 12, reactive form, when selecting Yes for Adult, user is required to enter an age, else no need.
HTML:
Are you adult?
<input type="radio" formControlName="Adult" value="1"/><label>Yes</label>
<input type="radio" formControlName="Adult" value="0"/><label>No</label>
<div *ngIf="fg.controls['Adult'].value==1">
Enter your age: <input type="text" placeholder="18-120" formControlName="Age" size="5"/>
</div>
TS:
public fg: FormGroup;
this.fg = this.fb.group
(
{
Adult: ['', [Validators.required]],
Age: ['', [Validators.required, Validators.min(18), Validators.max(120)]]
}
)
Angular is not smart enough to ignore validation because of hide/show. Formgroup fg.valid is false when user selects No, even though Age is hidden. One way to handle this dynamic thing is to hardcode the logic with addValidators([...]) / clearValidators() / setValidators([...]) then updateValueAndValidity().
Is there a better way?
Update
What I want is Angular to skip below validation rule when user chooses Yes because Age is hidden.
Age: ['', [Validators.required, Validators.min(18), Validators.max(120)]]
To achieve that, I now have to
- attach a
(blur)=dynamicAge()toAdultradio button - inside
dynamicAge()to check and set validation rule forAgelike below.
TS
private dynamicAge()
{
if (fg.controls['Adult'].value == 0) // not Adult
{
fg.controls['Age'].clearValidators(); // so fg.valid becomes true.
fg.controls['Age'].updateValueAndValidity();
}
}
Is there a better way?