Abx
Abx

Reputation: 2882

Allow user to type in only the options in mat-autocomplete in angular 6

I am using mat-autocomplete.

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

Was wondering if there is a way to restrict the user only to type in the options provided in the drop down ie. one,two and three only.When the user types anything else like sixteen then it shouldn't be displayed

 export class AutocompleteSimpleExample {
  myControl: FormControl = new FormControl();

  options = [
    'One',
    'Two',
    'Three'
   ];

}

Upvotes: 2

Views: 3775

Answers (1)

klevendoglu
klevendoglu

Reputation: 622

You may bind to blur event and check if the input value equals to desired input like below. I've used similar approach on my own autocomplate.

<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" (blur)="InputControl($event)" [matAutocomplete]="auto">

in component

InputControl(event) {
    setTimeout(() => {
        let isValueTrue = this.options.filter(myAlias =>
            myAlias  === event.target.value);
        if (isValueTrue.length === 0) {
            this.form.get(‘MyControl’).setValue(null);
        }
    }, 300);
}

Upvotes: 6

Related Questions