We have an autocomplete input with required
validation. When a user searches for an option by entering a query (but doesn't pick any of the options) then the input is valid, even though it doesn't match any of the suggested options.
What I want to achieve is not permitting the user to post the form unless one of the suggested options is selected. How do I achieve this?
<mat-form-field>
<input matInput placeholder="Pick one" aria-label="pick one" [matAutocomplete]="auto" [formControl]="form.controls['SELECTBOX_VALUE']">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of myOptions | async" [value]="option.name"> <span>{{ option.name }}</span> </mat-option>
</mat-autocomplete>
</mat-form-field>
<small *ngIf="!form.controls['SELECTBOX_VALUE'].valid && form.controls['SELECTBOX_DEGER'].touched" class="mat-text-warn">Please select.</small>
ngOnInit() {
this.form = this.fb.group({
... some other fields
SELECTBOX_VALUE: [null, Validators.required]
});
My filter code for Autocomplate is pretty straight forward:
this.form.get('SELECTBOX_VALUE').valueChanges
.pipe(
startWith(''),
map(option => secenek ? this.doFilter(option) : this.options.slice())
);
doFilter (name: string) {
return this.myOptions.filter(option =>
option.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}