Jack
Jack

Reputation: 1

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.

Upvotes: 1

Views: 2778

Answers (2)

challamzinniagroup
challamzinniagroup

Reputation: 73

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.

Upvotes: 0

Elmehdi
Elmehdi

Reputation: 1430

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:
enter image description here

With error "incorrect" if you don't select one of the options:
enter image description here

Error still present if you type the option instead of clicking on it:
enter image description here

No error if you click on the wanted option:
enter image description here

Here is the live demo

Upvotes: 1

Related Questions