簡體   English   中英

當我們從角度材質墊菜單中選擇任何項目時,焦點將從元素中移除

[英]Focus is being removed from the element when we select any item from the angular material mat menu

我有一個文本框和材料菜單。 當我們從材質菜單中選擇任何項目時,我將焦點設置在文本框上。 但是當材質菜單關閉時,對文本框的關注也會被移除。 如何防止這種行為?

我在單擊菜單項時嘗試了event.stopPropagation() ,但沒有奏效。 有什么建議?

我希望即使在關閉材料菜單后也應該關注文本框。

<input type="text" #someTextInput (focusout)="focusedOut()">

<button mat-icon-button [matMenuTriggerFor]="menu"> 
  <!-- pass local reference of mat-menu to be opened on this click -->
  <mat-icon>more_vert</mat-icon>
</button>

<mat-menu #menu="matMenu">
  <!-- give local reference and tell this is manu by assigning 'matMenu' -->
  <button mat-menu-item>
    <mat-icon>dialpad</mat-icon>
    <span>Redial</span>
  </button>
  <button mat-menu-item disabled>
    <mat-icon>voicemail</mat-icon>
    <span>Check voicemail</span>
  </button>
  <button mat-menu-item (click)="focusElement()">
    <mat-icon>notifications_off</mat-icon>
    <span>Disable alerts</span>
  </button>
</mat-menu>

.ts 文件

@Component({
  selector: 'menu-icons-example',
  templateUrl: 'menu-icons-example.html',
  styleUrls: ['menu-icons-example.css'],
})
export class MenuIconsExample implements AfterViewInit {

  @ViewChild('someTextInput') textInput: ElementRef;

  public ngAfterViewInit() {
    this.textInput.nativeElement.focus();
  }

  focusElement() {
    this.textInput.nativeElement.focus();
    console.log('focused...');
  }

  focusedOut() {
    console.log('focused out called...');
  }
}

請找到示例Stackblitz

好吧,您使用的角度材料版本存在錯誤(或不需要的行為)。 在菜單關閉事件之后,某些東西會導致輸入再次失去焦點。 您可以通過刪除示例中的setTimeout部分來觀察它。 有一個使用setTimeout解決方法,如下所示:

在您的模板中添加一個關閉的事件處理程序:

<mat-menu #menu="matMenu" (closed)="onMenuClosed()"> 

然后在您的組件類中:

 onMenuClosed() {
    setTimeout(() => {
      this.focusElement();
    });
  }

這是 Stackblitz 示例

請注意,更高版本的 angular-material 菜單有一個名為restoreFocus選項,它會自動將焦點恢復到以前的目標。

我想當你點擊一個菜單項時; angular 首先調用 click 方法,然后調用菜單的 close 方法,導致失去輸入焦點。 像這樣更改 focusElement 方法就可以解決問題:

focusElement() {
const nativeEl = this.textInput.nativeElement;

setTimeout(function () {
  nativeEl.focus();
  console.log('focused...');
}, 1);  

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM