0

I'm use Angular 9, how i manage to open menu, with click for Mobile and hover for Desktop?

For example, if i have a list of Items, i want to open menu with the hover when is desktop size, and this i manage with 'hover', but when i have mobile i want to open the menu with a click, considering i have more then one button so i don't want to have two different button for manage the actions Regards

corsaro
  • 731
  • 1
  • 9
  • 24
  • This right here should help you: [Show DIV on-hover on Desktop and on-click on Mobile](https://stackoverflow.com/questions/21153243/show-div-on-hover-on-desktop-and-on-click-on-mobile) – maersux Mar 06 '20 at 14:38

2 Answers2

1

I think the easiest and fastest is to implement media query css, but that's what you don't want. Then you can create a service that manages breakpoints and reuse it where you need it. It would be something similar to this:

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);
  }


}

And in yours components use like this:

this.breakpointsService.isMobile$()
  .pipe(
    takeUntil(this.unsubscribe$)
  )
  .subscribe(value => {
    this.isMobile = value;
  });
-1

As a workaround, you can check if the user is on mobile or desktop, then, apply the requested functionality to each one.

Use the ngOnInit hook on your component to verify:

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
  }
}

Hope this helps.

Leandro Soriano
  • 669
  • 1
  • 6
  • 14