【发布时间】:2018-12-25 16:37:15
【问题描述】:
我有一个带有click 的组件。
<my-box (click)="openModal()"></my-box>
当我点击这个元素时,openModal 函数将运行。
而且我想给 1000 毫秒的节流时间,以防止打开多个模式。
我的第一种方法是使用Subject(来自 rxJs)
//html
<my-box (click)="someSubject$.next()"></my-box>
//ts
public someSubject$:Subject<any> = new Subject();
...etc subscribe
但我觉得有点冗长。
下一个方法是使用directive。
我修改了一些通过谷歌搜索找到的代码。
//ts
import {Directive, HostListener} from '@angular/core';
@Directive({
selector: '[noDoubleClick]'
})
export class PreventDoubleClickDirective {
constructor() {
}
@HostListener('click', ['$event'])
clickEvent(event) {
event.stopPropagation(); // not working as I expected.
event.preventDefault(); // not working as I expected.
event.srcElement.setAttribute('disabled', true); // it won't be working unless the element is input.
event.srcElement.setAttribute('style', 'pointer-events: none;'); // test if 'pointer-events: none' is working but seems not.
setTimeout(function () {
event.srcElement.removeAttribute('disabled');
}, 500);
}
}
//html
<my-box noDoubleClick (click)="openModal()"></my-box>
但是,无论我尝试什么,总是openModal 被执行。
我找不到如何在指令中停止执行openModal。
我会喜欢的
//ts
//In the openModal method.
openModal() {
public isClickable = true
setTimeout(() => {
this.newsClickable = true;
}, 1000);
...
}
但对于可重用的代码,我认为 using 指令是理想的。
我该怎么做?
【问题讨论】:
标签: angular rxjs angular-directive