Artur Stary
Artur Stary

Reputation: 744

How to detect a middle click on a div in Angular2?

Suppouse we have this template:

<div class="myClass" (click)="doSomething($event)">

soSomething is not called on a middle click. How can I solve this problem?

Upvotes: 6

Views: 12518

Answers (2)

thegnuu
thegnuu

Reputation: 817

I solved this problem by using a small custom middleclick directive which is listening to the mouseup event because in my example (on macOS) the click HostListener is not fired on a middle click.

import { Directive, Output, EventEmitter, HostListener } from '@angular/core';

@Directive({ selector: '[middleclick]' })
export class MiddleclickDirective  {
  @Output('middleclick') middleclick = new EventEmitter();

  constructor() {}

  @HostListener('mouseup', ['$event'])
  middleclickEvent(event) {
    if (event.which === 2) {
      this.middleclick.emit(event);
    }
  }
}

With this you can use something like

<button (middleclick)="doSomething()">Do something</button>

Upvotes: 24

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657338

This should work

<div class="myClass" (click)="$event.which == 2 ? doSomething($event) : null">

See also Triggering onclick event using middle click

update 2/2018

When I posted above answer I was working on a Linux machine and it worked for me.

Now I'm on a Mac and I'm not able to get a click event for anything else than the left mouse button.

You can try it yourself using

StackBlitz example

See also

Upvotes: 3

Related Questions