I'm having trouble with conditional validation using template forms in Angular. I've created a custom EmailInputComponent:
<div class="form-group" provide-parent-form>
<label for="email">Email<span *ngIf="required">*</span></label>
<input id="email"
class="form-control"
name="email"
type="email"
[(ngModel)]="emailAddress"
#email="ngModel"
maxlength="255"
validateEmail
[required]="required ? '' : null"/>
<error [model]="email" [referencedValue]="emailAddress"></error>
</div>
which is hosted inside a parent MyFormComponent:
<form #form="ngForm" name="form" (ngSubmit)="onSubmit($event)">
<fieldset>
<email [(emailAddress)]="model.email" [required]="emailRequired()"></email>
<!-- select component here -->
</fieldset>
<button type="submit" [disabled]="!form.form.valid">Send</button>
</form>
The form also contains a SelectComponent where users can choose their preferred way of contact. If users select "email", the email input becomes mandatory.
As you can, see there is some logic going on in the parents emailRequired function that dynamically calculates whether an email input is mandatory or not based on the currently selected preferred way of contact. Whenever this selected value changes I need to somehow trigger the email input validators. How can I do that?
Using @ViewChild I managed to get a hold of the EmailInputComponent from the MyFormComponent. But I don't know how to proceed now...