I have a reactive form written in Angular 6. I have an input text field that has a custom validator. The validator works correctly. The text field contains a dropdown list. If the user enters data not in the list and tabs to the next field, the validator display an error ('location not valid').
I would like the invalid data in the text box to be cleared once the user tabs to the next field and the invalid error message display. This is the HTML:
<input
type="text"
matInput
formControlName = 'originControl'
[(ngModel)]="originId"
[matAutocomplete]="autoOrigin"
id="mat-card__origin-input-id"
/>
<mat-autocomplete autoActiveFirstOption #autoOrigin="matAutocomplete">
<mat-option *ngFor="let option of originOptions | async" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
<mat-error *ngIf="scheduleForm.controls['originControl'].hasError('invalid')" id="mat-error__origin">
Please select a valid location
</mat-error>
This is the validator function:
export function ValidateLocation(locationArray: Array<any>): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if ((control.value !== undefined || control.value !== null || control.value !== "") &&
(locationArray.indexOf(control.value) == -1)) {
return { 'invalid': true };
}
return null;
}
}
This is the typescript that creates the FormControl:
this.scheduleForm = new FormGroup({
'originControl': new FormControl(null, [ValidateLocation(this.fetchDataService.locationArray)])
});
How to clear the data in the control and leave the error message?