代码之家  ›  专栏  ›  技术社区  ›  Téwa

如何防止在角度上双击?

  •  4
  • Téwa  · 技术社区  · 6 年前

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

    然而,无论我怎么尝试,总是 开放模式 已执行。 我找不到停止执行的方法 开放模式 在指令中。

    我只是想

    //ts
    //In the openModal method.
    openModal() {
        public isClickable = true
    
        setTimeout(() => {
            this.newsClickable = true;
        }, 1000);
        ...
    }
    

    但是对于可重用代码,我认为使用指令是理想的。

    我怎么能做到?

    2 回复  |  直到 6 年前
        1
  •  13
  •   Sam Herrmann    6 年前

    debounce debounceTime Here

    import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, 
    Output } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    import { Subscription } from 'rxjs/Subscription';
    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>
    
        2
  •  4
  •   repo    6 年前

    throttleTime