我正在使用Angular 9,我如何管理打开菜单,单击移动和悬停桌面?
例如,如果我有一个项目列表,我想要在桌面大小时用鼠标悬停打开菜单,这是我用' hover‘管理的,但当我有移动设备时,我想用点击打开菜单,考虑到我有多个按钮,所以我不想有两个不同的按钮来管理操作
发布于 2020-03-06 23:49:58
我认为最简单和最快的是实现媒体查询css,但这是你不想要的。然后,您可以创建一个管理断点的服务,并在需要的地方重用它。它将类似于以下内容:
import { Injectable } from '@angular/core';
import { BreakpointObserver, BreakpointState, Breakpoints } from '@angular/cdk/layout';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BreakpointsService {
isMobile: Subject<boolean> = new Subject();
constructor(
private breakpointObserver: BreakpointObserver,
) {
this.breakpointObserver
.observe([
Breakpoints.XSmall
])
.subscribe((state: BreakpointState) => {
if (state.matches) {
// console.log('isMobile');
this.isMobile.next(true);
} else {
// console.log('not isMobile');
this.isMobile.next(false);
}
});
}
isMobile$() {
return this.isMobile.asObservable();
}
isMatchedMobile() {
const rta = this.breakpointObserver.isMatched([Breakpoints.XSmall]);
this.isMobile.next(rta);
}
}在您的组件中使用如下所示:
this.breakpointsService.isMobile$()
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe(value => {
this.isMobile = value;
});发布于 2020-03-07 00:09:42
作为一种解决办法,您可以检查用户是在移动设备上还是在桌面上,然后将请求的功能应用到每个设备上。
使用组件上的ngOnInit挂钩验证:
ngOnInit(): void {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
// Logic for mobile users using on click
} else {
// Logic for desktop users using on hover
}
}希望这能有所帮助。
https://stackoverflow.com/questions/60566237
复制相似问题