简体   繁体   中英

How to detect mat-autocomplete option is selected in Angular?

I tried this approach in order to apply validation to Material Autocomplete. But the part used for detecting if the value is selected or not by comparing the type is not working:

import { AbstractControl } from '@angular/forms';

export function RequireMatch(control: AbstractControl) {
    const selection: any = control.value;
    if (typeof selection === 'string') {
        return { incorrect: true };
    }
    return null;
}

When debugging the app, typeof selection === 'string' line always returns true - it doesn't matter if the option is selected or not. Any idea how to check it? The testable app is available on StackBlitz .

For me it works Just fine, as soon as you click the wanted option there is no error.
note that you have to click on the wanted option and not just write it.

Normal with two error:
在此处输入图片说明

With error "incorrect" if you don't select one of the options:
在此处输入图片说明

Error still present if you type the option instead of clicking on it:
在此处输入图片说明

No error if you click on the wanted option:
在此处输入图片说明

Here is the live demo

Just to add to this, I've modified the validator function to the following:

  private _autocompleteValidator(control: AbstractControl) {
    return control.value && typeof control.value === 'string'
      ? { autocomplete: true }
      : null;
  }

Adding the control.value && ... to the check allows for the input (whether partially typed or previously selected) to be cleared and pass validation.

The purpose of this validator should only be to force the value to be a selection from the autocompleter, if a value is entered .

If the particular field in question is required, that should be configured through a separate, standard Validators.required .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM