Compiler v2
Compiler v2

Reputation: 3605

Is there a way to disable typing for autocomplete? - Angular Material

I have the following autocomplete in Angular material:

 <!-- Drop Down menu -->
          <mat-form-field>
            <input placeholder="Select one" [matAutocomplete]="auto" matInput>

            <mat-autocomplete #auto="matAutocomplete">
              <mat-option value="Cars">Cars</mat-option>
              <mat-option value="Books">Books</mat-option>
            </mat-autocomplete>
          </mat-form-field>

Is there a way to disable typing on the input so that the user does not defeat the purpose of the dropdown menu? Right now, the user can just type something instead of picking an option, or even edit an option when selected.

Upvotes: 6

Views: 21449

Answers (6)

Mohamed Elmancy
Mohamed Elmancy

Reputation: 311

You have to put readonly on the input.

Upvotes: 2

Apisart Chanpuang
Apisart Chanpuang

Reputation: 11

you can set maxlength="0", and options are still possible to be selected.

Upvotes: 1

Kunal Rode
Kunal Rode

Reputation: 31

Yes, you can. To do so, in the ngOnit function, disable the reactive form control for that field:

this.myControl.disable()

Upvotes: 3

Crystal
Crystal

Reputation: 1505

Yes there is

Here is the documentation with an example to disable the autocomplete input

https://material.angular.io/components/autocomplete/examples

I needed to disable the input after a selection and I couldn't use a mat-select because I had over 600 options... so the autocomplete / typeahead was needed. Can't use mat-chips either because only one selection can be picked at one time.

stackblitz = https://stackblitz.com/angular/kopovlnpxapb?file=src%2Fapp%2Fautocomplete-overview-example.ts

Upvotes: 13

indrajeet
indrajeet

Reputation: 897

  1. If you want input field to disable all the time then use normal select drop down

  2. If you want to use auto complete but don't want user to edit selected option in input field then you might wanna use chips autocomplete - https://material.angular.io/components/chips/examples

Upvotes: 0

Christian Benseler
Christian Benseler

Reputation: 8065

If you don't want the user to input anything in the input but instead only select from a list, why don't use a mat-select? The user can also select with the keyboard, typing what he needs. The docs: https://material.angular.io/components/select/overview

Upvotes: 0

Related Questions