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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With