Angular防抖指令
2022-01-15 本文已影响0人
我就是要学习
第一次在掘金上记笔记,使用Angular小半年了。深感Angular中文资料稀少,故记录一些文章供自己翻阅,同时希望能帮助到一些有需要的朋友
目标:在元素上直接对click等事件进行防抖处理
<button (debounceClick)="doSomething()">
思路:
- RxJS debounceTime操作符
- angular HostListener监听事件
代码实现:
<button nz-button (debounceClick)="logEvent($event)" [debounceTime]="1000">防抖测试</button>
<input nz-input (debounceKeyUp)="logEvent($event)" />
import { Directive, Input, OnDestroy, OnInit } from '@angular/core';
import { debounceTime, Subject, takeUntil } from 'rxjs';
@Directive()
export abstract class AbstractDebounceDirective implements OnInit, OnDestroy {
@Input() debounceTime = 300;
protected emitEvent$ = new Subject<Event>();
protected destroyed$ = new Subject<void>();
ngOnInit(): void {
this.emitEvent$
.pipe(debounceTime(this.debounceTime), takeUntil(this.destroyed$))
.subscribe((value) => this.emitValue(value));
}
abstract emitValue(event: Event): void;
ngOnDestroy(): void {
this.destroyed$.next();
this.destroyed$.complete();
}
}
import { Directive, EventEmitter, HostListener, Output } from '@angular/core';
import { AbstractDebounceDirective } from './abstract-debounce.directive';
@Directive({
// eslint-disable-next-line @angular-eslint/directive-selector
selector: '[debounceKeyUp]',
})
export class DebounceKeyupDirective extends AbstractDebounceDirective {
@Output() debounceKeyUp = new EventEmitter<Event>();
constructor() {
super();
}
@HostListener('keyup', ['$event'])
onClick(event: KeyboardEvent): void {
event.preventDefault();
this.emitEvent$.next(event);
}
emitValue(event: Event): void {
this.debounceKeyUp.emit(event);
}
}
import { Directive, EventEmitter, HostListener, Output } from '@angular/core';
import { AbstractDebounceDirective } from './abstract-debounce.directive';
@Directive({
// eslint-disable-next-line @angular-eslint/directive-selector
selector: '[debounceClick]',
})
export class DebounceClickDirective extends AbstractDebounceDirective {
@Output() debounceClick = new EventEmitter<Event>();
constructor() {
super();
}
@HostListener('click', ['$event'])
onClick(event: MouseEvent): void {
event.preventDefault();
this.emitEvent$.next(event);
}
emitValue(event: Event): void {
this.debounceClick.emit(event);
}
}