This is either what you want or very close to it:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { fromEvent } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild('mybutton') button: ElementRef;
ngAfterViewInit() {
fromEvent(this.button.nativeElement, 'dblclick')
.subscribe(e => console.log('double click'));
fromEvent(this.button.nativeElement, 'click')
.subscribe((e: MouseEvent) => {
if (e.detail === 1) console.log('one click') // could use a filter inside a pipe instead of using an if statement
// if (e.detail === 2) console.log('double click') // an alternative for handling double clicks
});
}
}
and the HTML:
<button #mybutton>Test</button>
This solution uses event.detail and is loosely based on this useful post - Prevent click event from firing when dblclick event fires - which not only discusses event.detail but also looks at the timing issues involved.
One of the big probs with your code is that you are subscribing to the event inside a function that is called multiple times, which means each time the button is clicked you create another subscription. Using ngAfterViewInit
(which is only called once as part of the lifecycle) prevents this issue (and ensures the DOM is loaded).
Here's a stackblitz for you:
https://stackblitz.com/edit/angular-t6cvjj
Forgive me for my sloppy type declarations!
This satisfies your requirements as follows:
- If I click once, I need to see only one message ('one click') - PASS
- If I click twice (doubleclick), still I need to see only one message ('double click') - FAIL, you see 'one click' on the 1st click and 'double click' on the 2nd click
- If I click more than twice - nothing happens - PASS
Due to the timing issues discussed in the SO post given, how you solve this is a matter of preference and thus I decided not to tackle it. And plus, you are not paying me ;) This answer however should set you well on your way to solving it fully.
PS There is a comment on the SO post above that suggests event.detail may not work on IE11