Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show autocomplete dropdown only after type at least 1 letter in Angular 2+

I would like to implement an autocomplete using Angular 2+ with angular material design where the options should not appear unless they've typed at least 1 letter.

By default, the autocomplete is toggleable on focus even when the input is empty, so I want to change this behavior.

I have tried to add a condition on mat-autocomplete element *ngIf="inputField.value" in order to display the options only if the input has value, but it returns the error:

Error: Attempting to open an undefined instance of mat-autocomplete. Make sure that the id passed to the matAutocomplete is correct and that you're attempting to open it after the ngAfterContentInit hook.

Also, I have tried to add a condition into [matAutocomplete]="auto" on the input field, but it also returns error.

I noticed that when the autocomplete options are being displayed, the elements cdk-overlay-container and mat-autocomplete-panel are created before close </body>, and they are unlinked with the original component, so it difficult to hide by css.

Do you have ideas how to do that?

Please follow the code on Stackblitz.

Thanks!

like image 927
Dwcps Avatar asked Apr 12 '18 13:04

Dwcps


People also ask

How does angular validate autocomplete?

Create custom validator for autocomplete Working with reactive forms, the easiest way to solve this issue is to write a custom form validator. This function evaluates the value of a control and return a validation error if the value is a string type.

How do you close an autocomplete mat panel?

If you press on tab while typing, the cursor will move onto the next editable element and the panel (dropdown) of the latest element will close.


1 Answers

Do not call the filter function if the typed text's length equals 0.

this.filteredOptions = this.myControl.valueChanges
  pipe(
     startWith(''),
     map(val => val.length >= 1 ? this.filter(val): [])
);

Demo

like image 190
Tomasz Kula Avatar answered Nov 16 '22 02:11

Tomasz Kula