gpt4 book ai didi

angular - 如何防止在 Angular 中双击?

转载 作者:太空狗 更新时间:2023-10-29 17:16:08 30 4
gpt4 key购买 nike

我有一个带有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

但我觉得它有点冗长。

下一个方法是使用指令。我修改了一些通过谷歌搜索找到的代码。

//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 指令是理想的。

我怎样才能做到?

最佳答案

由于有人要求使用throttleTime 指令,我将在下面添加它。我选择走这条路是因为 debounceTime 在触发实际点击事件之前等待最后一次点击。 throttleTime 将不允许答题器再次单击按钮,直到达到该时间,而是立即触发单击事件。

指令

import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { throttleTime } from 'rxjs/operators';

@Directive({
selector: '[appPreventDoubleClick]'
})
export class PreventDoubleClickDirective implements OnInit, OnDestroy {
@Input()
throttleTime = 500;

@Output()
throttledClick = new EventEmitter();

private clicks = new Subject();
private subscription: Subscription;

constructor() { }

ngOnInit() {
this.subscription = this.clicks.pipe(
throttleTime(this.throttleTime)
).subscribe(e => this.emitThrottledClick(e));
}

emitThrottledClick(e) {
this.throttledClick.emit(e);
}

ngOnDestroy() {
this.subscription.unsubscribe();
}

@HostListener('click', ['$event'])
clickEvent(event) {
event.preventDefault();
event.stopPropagation();
this.clicks.next(event);
}
}

示例用法

throttleTime 是可选的,因为指令中有默认值 500

<button appPreventDoubleClick (throttledClick)="log()" [throttleTime]="700">Throttled Click</button>

如果您有一个每 1 毫秒点击您的元素的机器人,那么您会注意到该事件只会触发一次,直到 throttleTime 结束。

关于angular - 如何防止在 Angular 中双击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51390476/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com