我编写了以下代码来消除和延迟按钮按下的垃圾邮件:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句