首页 > 解决方案 > 如何将按钮单击去抖动延迟转换为文本框按键延迟?

问题描述

我编写了以下代码来消除和延迟按钮按下的垃圾邮件:

app.directive.ts

// Debounce click method for buttons to prevent spamming during asynchronous function waits

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);
  }
}

app.component.html

<button mat-raised-button appDebounceClick (debounceClick)="buttonPressed()" [debounceTime]="700">Example Button</button>

我的最终目标是有一个文本框,它只会在用户停止输入一定秒数后才调用一个函数(非常类似于按钮)。我将如何制定类似的指令来代替文本框按键而不是按钮单击的发短信?

编辑:

这是我当前的输入文本框 HTML(未去抖动):

<form class="form">
  <mat-form-field class="full-width" (keyup)="exampleFunction('exampleInputString')">
    <input matInput placeholder="Input something...">
  </mat-form-field>
</form>

标签: javascripthtmlangulartypescript

解决方案


解决方案相当简单。

指令.ts:

// Change click event to keyup event

@HostListener('click', ['$event'])@HostListener('keyup', ['$event'])

组件.html:

<form class="form">
  <mat-form-field class="full-width" appDebounceClick (debounceClick)="exampleFunction('exampleInputString')" [debounceTime]="700">
    <input matInput placeholder="Input something...">
  </mat-form-field>
</form>


推荐阅读