Implementing custom validation for auto-completion in a template-driven form.
The challenge: the validator function is being triggered with the previous user input value.
HTML
<mat-form-field *ngIf="configObj(controls)['type']=== 'employees'">
<input matInput #employeesf [matTooltip]="configObj(controls)['tooltip']||controls" placeholder="{{controls}}"
formControlName="{{controls}}"
[required]="configObj(controls)['require']==='yes'|| configObj(controls)['require']==true "
(ngModelChange)="_filterEmployees(employeesf.value)" [matAutocomplete]="employeeInput"
placeholder="{{'translate.select_employee' | translate}}" required appHasSelectedOptionValidator
[options]="filteredClients" [userInput]="[clientf.value]" />
<mat-autocomplete panelWidth="auto" #employeeInput="matAutocomplete" (optionSelected)="employeeClick($event)">
<mat-option *ngFor="let employee of filteredEmployees" [value]="employee">
{{employee}}
</mat-option>
</mat-autocomplete>
<mat-hint *ngIf="configObj(controls)['display_old_answer']">{{hints[controls]}}</mat-hint>
<mat-hint *ngIf="!configObj(controls)['display_old_answer'] && configObj(controls)['hint']">
{{configObj(controls)['hint']}}
</mat-hint>
</mat-form-field>
TS (hasSelectedOptionValidator.ts)
import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator } from '@angular/forms';
@Directive({
selector: '[appHasSelectedOptionValidator]',
providers: [
{ provide: NG_VALIDATORS, useExisting: HasSelectedOptionValidatorDirective, multi: true }
]
})
export class HasSelectedOptionValidatorDirective implements Validator {
@Input("options") options: string[]
@Input("userInput") userInput: any
validate(c: FormControl) {
console.log('options ', this.options)
console.log('input ', this.userInput)
let subby = [];
this.options.forEach(element => subby.push(element[0]));
console.log('sub: ', subby);
if (subby.includes(this.userInput[0])) {
console.log('in');
return null;
} else {
console.log('not in')
console.log('subby ', subby)
console.log('input ', this.userInput[0])
return { 'selected': false };
}
}
}
Is there a way to update the validation check based on the most recent user input, especially when the user selects an option from the auto-completion menu?