gpt4 book ai didi

javascript - 在指令中禁用不重置

转载 作者:行者123 更新时间:2023-12-02 22:45:45 25 4
gpt4 key购买 nike

关注此Stackblitz

我有一个指令,当您单击时,它应该在特定时间之前禁用该按钮(以防止双击)。

<button appThrottleClick (throttleClick)="click()">
BUTTON
</button>

<button appThrottleClick [disabled]="myValue" (throttleClick)="click()">
BUTTON VALUE
</button>

我希望禁用该按钮,然后在 x 秒后重新启用。在这里使用这个指令:

@Directive({
selector: '[appThrottleClick]'
})
export class ThrottleClickDirective implements OnInit, OnDestroy {
@HostBinding('attr.disabled') disabled: boolean;

@Input() throttleTime = 200;

@Output() throttleClick = new EventEmitter();

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

constructor() { }

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

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

@HostListener('click', ['$event'])
clickEvent(event) {
console.log('click')
if (this.disabled) { return; }
event.preventDefault();
event.stopPropagation();
this.disabled = true;
this.clicks.next(event);
setTimeout(() => { this.disabled = false; console.log('reset')}, this.throttleTime);
}
}

基本上:

如果该按钮未禁用,请单击一次,然后设置冷却时间并再次重新启用它。如果该按钮被禁用,请勿单击。

我面临的问题是,点击并等待冷却后,它再也不会重新启用。即使禁用也设置为 false。

最佳答案

不要使用 @HostBinding 我们使用 ElementRef 来禁用和启用该按钮,这样您的指令将是

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

@Directive({
selector: '[appThrottleClick]'
})
export class ThrottleClickDirective implements OnInit, OnDestroy {
@Input() throttleTime = 1000;

@Output() throttleClick = new EventEmitter();

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

constructor(private _elementRef:ElementRef) { }

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

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

@HostListener('click', ['$event'])
clickEvent(event) {
console.log('click')
event.preventDefault();
event.stopPropagation();
this._elementRef.nativeElement.disabled=true;
this.clicks.next(event);
setTimeout(() => {
console.log('reset')
this._elementRef.nativeElement.disabled=false;
}, this.throttleTime);
}
}

demo

关于javascript - 在指令中禁用不重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58405616/

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