首页 > 解决方案 > 按下tab键时如何选择mat选项?,它应该像mat-autocomplete angular 6中的输入按钮一样工作

问题描述

我们如何在按下 tab 键时选择 mat 选项?它应该像 mat-autocomplete angular 6 中的 enter 按钮一样工作......

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

演示

标签: javascriptangularangular-materialmaterial-designangular-material2

解决方案


你可以订阅 this.autoTrigger.panelClosingActions,见stackblitz

如果你的 .html 就像

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

在你的 .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)
      }
    } )
  }

在此答案中更新更好的方法(使用指令)


推荐阅读