我有一个文本框和 Material 菜单。当我们从 Material 菜单中选择任何项目时,我将焦点设置在文本框上。但是当 Material 菜单关闭时,文本框上的焦点也会被删除。如何防止这种行为?
我在菜单项点击上尝试了 event.stopPropagation()
,但没有成功。有什么建议吗?
我希望即使在 Material 菜单关闭后,文本框的焦点也应该出现。
<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
最佳答案
您正在使用的 Angular-Material 版本存在错误(或不需要的行为)。菜单关闭事件后,某些原因导致输入再次失去焦点。您可以通过删除示例中的 setTimeout
部分来观察它。有一个使用 setTimeout
的解决方法,如下所示:
在您的模板中添加一个关闭的事件处理程序:
<mat-menu #menu="matMenu" (closed)="onMenuClosed()">
然后在你的组件类中:
onMenuClosed() {
setTimeout(() => {
this.focusElement();
});
}
这是 Stackblitz example
请注意,更高版本的 Angular-Material 菜单具有名为 restoreFocus
的选项,该选项会自动将焦点恢复到先前的目标。
关于javascript - 当我们从 Angular Material 垫菜单中选择任何项目时,焦点将从元素中移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59374089/