且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止在 Angular 中双击?

更新时间:2023-10-29 15:19:28

你可以使用 RxJs 的 debouncedebounceTime 运算符以防止双击.这里也是一篇关于如何创建的帖子自定义去抖动点击指令.

You can use RxJs' debounce or debounceTime operator to prevent double clicks. Here is also a post on how to create a custom debounce click directive.

万一帖子被撤下,这里是最终代码:

In case the post is taken down in the future, here is the final code:

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

@Directive({
  selector: '[appDebounceClick]'
})
export class DebounceClickDirective implements OnInit, OnDestroy {
  @Input() 
  debounceTime = 500;

  @Output() 
  debounceClick = new EventEmitter();
  
  private clicks = new Subject();
  private subscription: Subscription;

  constructor() { }

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

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

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

示例用法:

<button appDebounceClick (debounceClick)="log()" [debounceTime]="700">Debounced Click</button>