我正在尝试设置属性指令来处理单击并双击同一元素。不知道如何建立与模板的连接,我已经声明了,我将ClickTwiceDirective放在HTML标签中。此外,如果有更好的方法,我很感兴趣。我认为最好避免点击并双击相同的元素,但这是要求和需要设计的内容(单击选择,双击可编辑)。
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';
@Directive({
selector: '[clickTwice]'
})
export class ClickTwiceDirective {
clickedElement: number = 0;
constructor(private _elementRef : ElementRef) {
}
@Output()
public singleClick = new EventEmitter();
public doubleClick = new EventEmitter();
@HostListener('this._elementRef:click', ['$event.target'])
public onClick(targetElement: any) {
console.log('got here');
this.clickedElement++;
setTimeout(() =>{
if(this.clickedElement < 2){
this.singleClick.emit(null);
this.clickedElement = 0;
} else {
this.doubleClick.emit(null);
this.clickedElement = 0;
}
}, 300);
}
}
我认为应该看起来的HTML输入示例
<input type="text" (singleClick)='func1()' (doubleClick)="func2()" clickTwice/>
答案 0 :(得分:1)
您是否有理由不能使用(dblclick)
和(click)
?
https://angular.io/docs/ts/latest/guide/user-input.html
答案 1 :(得分:1)
此指令基于您的开头帖子+此帖子how to differentiate single click event and double click event?应该有效。 这是一个有完整工作示例https://plnkr.co/edit/8GlMhEriNcGuKShEzL9h?p=preview
的傻瓜@Directive({
selector: '[detectclick]'
})
export class DetectClickDirective {
clickCount: number = 0;
clickTimeout: any = null;
@Input('detectclick') public detectclick:any;
@Output() public singleClick = new EventEmitter();
@Output() public doubleClick = new EventEmitter();
constructor(private _elementRef : ElementRef) {
}
@HostListener('click', ['$event.target'])
public handleClick(targetElement: any) {
this.clickCount++;
// Reset on every click
if (this.clickTimeout !== null) {
clearTimeout(this.clickTimeout);
}
// Detect type of click in x mili seconds
this.clickTimeout = setTimeout(detectClickType.bind(this), 300);
function detectClickType () {
if (this.clickCount >= 2){
// detected a double click
this.doubleClick.emit();
}
else {
// detected single click
this.singleClick.emit();
}
// reset after each detect
this.clickCount = 0;
}
}
}