如何将按钮单击反跳延迟转换为文本框按键延迟?

时间:2019-07-12 15:24:21

标签: javascript html angular typescript

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

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>

2 个答案:

答案 0 :(得分:1)

解决方案非常简单。

directive.ts:

// Change click event to keyup event

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

component.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>

答案 1 :(得分:0)

即使在debounce上也直接将onChangeinput一起使用非常有效。像这样:

<input type="text" id="myId" onChange={debounce(400, functionToCall())}/>