Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we select mat option when press on tab key?, it should work like enter button in mat-autocomplete angular 6

How can we select mat option when press on tab key?, it should work like enter button in mat-autocomplete angular 6... In below URL its working when press enter, but whenever we press tab button it should select highlighted option.

<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>

Demo

like image 842
vinaykumar0459 Avatar asked Mar 08 '19 07:03

vinaykumar0459


People also ask

How do you clear mat autocomplete when no option is selected from autocomplete dropdown?

You can remove the formControl-binding from your input and when you select an option you set that id to your form. You are already calling such a function (onSelectionChange)="onEnteredAccount(accountOption)" in which you can do that.

How do you use autocomplete mat?

The <mat-option></mat-option> has the ngFor directive to loop through the list of articles which are then recommended when the user starts typing. In the above code, we first import our API service. We then define the autocomplete() function, which we use to make an API request to retrieve a list of articles.


1 Answers

You can subscribe to this.autoTrigger.panelClosingActions, see stackblitz

If your .html is like

<mat-form-field class="example-full-width">
    <!--see the reference variable-->
    <input #typehead type="text" ...>
    <mat-autocomplete #auto="matAutocomplete">
       ...
    </mat-autocomplete>
</mat-form-field>

In your .ts

@ViewChild( 'typehead', {read:MatAutocompleteTrigger})  autoTrigger: MatAutocompleteTrigger; 

ngAfterViewInit()
  {
    this.autoTrigger.panelClosingActions.subscribe( x =>{
      if (this.autoTrigger.activeOption)
      {
        console.log(this.autoTrigger.activeOption.value)
        this.myControl.setValue(this.autoTrigger.activeOption.value)
      }
    } )
  }

Update a better aproach (using a directive) in this answer

like image 74
Eliseo Avatar answered Oct 06 '22 20:10

Eliseo