How to disable the right mouse button event in Angular 7?

Asked

Viewed 855 times

0

I am trying to disable that menu that appears on the page when the user clicks with the right mouse button.

At Angular, I can catch the click event using (click)="onRightClick($event), but I only get the "Left Click" on $event.

Remembering that if I do HostListener('click') myClick(){ } is the same thing as (click)="myClick()

I searched the Angular and the @Hostlistener and I couldn’t find a solution.

Link to the @Hostlistener documentation: Angular - Hostlistener

This is the code where I take the click event, but it only takes the Left Click, when it is the Right Click, the code is not triggered.

@HostListener('click', ['$event'])
  onClick(event) {
    console.log(event);
  }

1 answer

2


The (click) as well as the parameter 'click' in @HostListener will execute as addEventListner, click event works even only with left click, if you want to make more iterations with mouse you should use mousedown, example:

@HostListener('mousedown', ['$event'])
teste(event: MouseEvent)
{
    switch (event.button) {
        case 1:
            console.log('Botão esquerdo do mouse! ');
            break;
        case 2:
            console.log('Botão direito do mouse! ');
            break;
        default:
            console.log('Outro botão de mouse (click no scroll, mouse gamer, etc)');
    }
}
  • Thanks for the help, your code worked, I just need a way to cancel the event. Either by executing the action again, or by hiding the menu that opens when right-clicking... anyway, if you have any command to handle this event, you are welcome to.

  • @Edwardramos would be within the method the teste(event: MouseEvent)
{ event.preventDefault();?

  • That’s right, only when I use event.preventDefault(); , nothing happens. It seems that this method does not work.

  • @Edwardramos wants to cancel which event?

  • Cancel the right-click event as preventDefaulr() is not working. I decided to hide Body when this event is triggered, It was the simplest way to solve this, but users will end up complaining that the page "some", anyway, It is what you can do so far. I will mark how validates your answer, because it was the one that helped me to reach the goal.

  • 1

    @Edwardramos did not imagine that the goal was to block the context menu, in case it is this way try @HostListener('contextmenu', ['$event']) and you can try it too: (contextmenu)="teste($event)" and apply preventDefault in the class: teste(event) { event.preventDefault(); }

  • Look, it worked! @Guilhermenascimento Thanks a lot for your help!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.