如何在Angular Material中将Tab键作为Enter键?

Ram*_*ran 1 html events autocomplete angular-material angular

这是我的角物料自动完成代码

<input type="search" id="setId" name="setId" [attr.list]='collectionType' [(ngModel)]="selValue" class="text-box"
  placeholder="--Select--" (focus)="ValidateParent()" (keyup.tab)="test()" (keyup)="EmitValues($event)" [id]="setId"
  [matAutocomplete]="auto" [title]="selValue" [placeholder]='WaterMarkText'>


<div [hidden]="IsCascading">
  <mat-autocomplete [id]="collectionType" #auto="matAutocomplete" (optionSelected)='onChange($event)'>
    <mat-option *ngFor="let items of codeList" [value]="items.text" [attr.data-text]='items.text' [id]="items.value">
      {{items.text}}
    </mat-option>
  </mat-autocomplete>
</div>
Run Code Online (Sandbox Code Playgroud)

角度材料的tab选择存在问题。例如,自动材料完成无法在单击tab按钮时选择值。但点击enter按钮即可正常工作。因此,我需要手动entertab键事件覆盖键事件。怎么可能?

Eli*_*seo 7

完善我的评论,并根据回复我们可以创建一个指令

import { Directive, AfterViewInit, OnDestroy, Optional } from '@angular/core';
import { MatAutocompleteTrigger } from '@angular/material';


@Directive({ selector: '[tab-directive]' })
export class TabDirective implements AfterViewInit, OnDestroy {
  observable: any;
  constructor(@Optional() private autoTrigger: MatAutocompleteTrigger) { }
  ngAfterViewInit() {
    this.observable = this.autoTrigger.panelClosingActions.subscribe(x => {
      if (this.autoTrigger.activeOption) {
        this.autoTrigger.writeValue(this.autoTrigger.activeOption.value)
      }
    })
  }
  ngOnDestroy() {
    this.observable.unsubscribe();
  }
}
Run Code Online (Sandbox Code Playgroud)

你用:

<input tab-directive type="text" matInput [formControl]="myControl" 
      [matAutocomplete]="auto" >
Run Code Online (Sandbox Code Playgroud)

(请参阅stackblitz

更新 我们只能控制tab.key,否则总是关闭,您会获得所选值,因此

@Directive({ selector: '[tab-directive]' })
export class TabDirective{
  observable: any;
  constructor(@Optional() private autoTrigger: MatAutocompleteTrigger) { }

  @HostListener('keydown.tab', ['$event.target'])onBlur()
  {
    if (this.autoTrigger.activeOption) {
        this.autoTrigger.writeValue(this.autoTrigger.activeOption.value)
      }
  }

}
Run Code Online (Sandbox Code Playgroud)

(请参阅新的Stackblitz)

更新2我不认为此答案有太多赞成票,因为它是错误的。正如@Andrew allen的注释一样,该指令不会更新控件。好,已经晚了,但我尝试解决。一种选择是使用

this.autoTrigger._onChange(this.autoTrigger.activeOption.value)
Run Code Online (Sandbox Code Playgroud)

另一个想法是注入ngControl,所以

  constructor(@Optional() private autoTrigger: MatAutocompleteTrigger,
              @Optional() private control:NgControl) { }
  ngAfterViewInit() {
    this.observable = this.autoTrigger.panelClosingActions.subscribe(x => {
      if (this.autoTrigger.activeOption) {
        const value=this.autoTrigger.activeOption.value;
        if (this.control)
          this.control.control.setValue(value,{emit:false});
        this.autoTrigger.writeValue(value);
      }
    })
  }
Run Code Online (Sandbox Code Playgroud)