要在Angular Material的下拉菜单获得焦点时禁用全局滚动,你可以使用@HostListener
监听器来捕获滚动事件,并在下拉菜单获得焦点时阻止默认的滚动行为。以下是一个示例解决方案:
ViewChild
和ElementRef
:import { Component, ViewChild, ElementRef } from '@angular/core';
ViewChild
装饰器获取下拉菜单元素的引用:@ViewChild('dropdownMenu') dropdownMenu: ElementRef;
@HostListener
监听器来捕获滚动事件:@HostListener('window:scroll', ['$event'])
onWindowScroll(event) {
// 阻止默认的滚动行为,如果下拉菜单获得焦点
if (this.dropdownMenu.nativeElement.contains(event.target)) {
event.preventDefault();
}
}
dropdownMenu
变量绑定到ViewChild
获取的下拉菜单元素:
通过以上步骤,你就可以在下拉菜单获得焦点时禁用全局滚动了。