首页 > 解决方案 > 如何通过单击移动设备和悬停桌面来管理打开菜单

问题描述

我正在使用 Angular 9,我如何设法打开菜单,点击移动设备并悬停桌面设备?

例如,如果我有一个项目列表,我想在桌面大小时用悬停打开菜单,我用“悬停”来管理,但是当我有移动设备时,我想通过点击打开菜单,考虑到我有不止一个按钮,所以我不想有两个不同的按钮来管理操作问候

标签: htmlcssangulartypescriptsass

解决方案


我认为最简单最快的是实现媒体查询 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;
  });

推荐阅读