I am using mat-auto complete component from material.angular.io. The default behavior is user can input any value as well as it gives options to choose from. Also you can add your input to chosen values. You can check example here. https://stackblitz.com/angular/ngmvgralayd?file=app%2Fautocomplete-simple- example.html
here is the code I am using for generating auto complete input field.
<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" disabled="true">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of options" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
But I want the form field to take only values from the given option and want to prevent from entering any values by users apart from given option. How to achieve this? It is like select input with auto complete feature.
I think there is a UI/UX question here - in what way do we prevent the user from typing something that is not in the list of options, but still allow them to filter by a string?
I see a couple of potential options. First one is to just display an error "Invalid entry" when the option isn't in the list adjacent to the input. The second option would be to actually prevent the entry of characters that no longer match any options. So if there is a single option "foo" and a user types "for", only "fo" would be accepted, and the 'r' gets thrown out.
The PrimeNg solution is not quite the same as a text field that allows a user to start typing on focus. The user needs to first click to open a search, and there appears to be no keyboard accessibility. I don't really see why they haven't implemented it such that display and the search are the same, except they've got logos displayed.
Markup:
Component:
The Material demo for chips autocomplete shows bindings on both the
input
and to themat-autocomplete
:If you only want to allow options from the autocomplete, just omit the
add
function from the input.As already suggested in comment by @trichetriche this is a use case for select.
You can use material version of select, like this
If you need filter above the select, than I suggest to you PrimeNg Dropdown https://www.primefaces.org/primeng/#/dropdown