javascript - 如何将按钮单击去抖动延迟转换为文本框按键延迟?
问题描述
我编写了以下代码来消除和延迟按钮按下的垃圾邮件:
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>
解决方案
解决方案相当简单。
指令.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>
推荐阅读
- delphi - 如果我的打印机是 TMetafilePrinter,如何获取纸张大小?
- javascript - 在前端 JS 中使用来自 Node.js / Express 后端的对象
- java - Java:当jaxb mvn插件不生成输入类进行操作时,如何调用不带参数的webservice方法?
- javascript - 在 Vercel 上部署 React 应用程序后出现空白屏幕
- c - 如何使用“fgetc”的返回类型来破坏代码?
- c++ - 使用 T[] 访问两个相邻声明的 T 类型对象是未定义的行为吗?
- .net - 从方形剃刀形式返回的应用程序错误
- azure - 公开 Blob 存储并上传到其中
- javascript - 如何为每个帖子自动创建带有新 URL 的子页面 [NodeJS]
- visual-studio - Visual Studio 2019 IDE 性能