踩坑实录---Angular防抖——点击事件
npx ng g directive DebounceClickDirective --module=app
然后自动生成了2 个文件
CREATE src/app/debounce-click-directive.directive.spec.ts (290 bytes)
CREATE src/app/debounce-click-directive.directive.ts (173 bytes)
检查一下
debounce-click-directive.directive.spec.ts
import { Directive, OnInit, HostListener, Output, EventEmitter, OnDestroy, Input, HostBinding } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; @Directive({ selector: '[appDebounceClick]' }) export class DebounceClickDirective implements OnInit, OnDestroy { @Input('appDebounceClick') debounceTime = 500; @Output() debounceClick = new EventEmitter(); private clicks = new Subject<any>(); 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); } @HostBinding() test() { // } }
再检查一下app.module.ts
src/app/
import { DebounceClickDirective } from './debounce-click-directive.directive';
@NgModule({
declarations: [AppComponent, DebounceClickDirective],
注意啊!!这里有个坑,有的项目是分模块的,注册到app.module有的时候也是不管用的,你需要注册到距离你需要用到的最近的模块,因为这个是按需引入的,
要不然你这个自定义指令是没卵用的哦!!!!
然后很简单
你的html就可以直接使用了
<button (click)="myappDebounceClick()">即刻執行</button> <button appDebounceClick (debounceClick)="myappDebounceClick()">使用默認時間間隔來執行</button> <button appDebounceClick (debounceClick)="myappDebounceClick()" [debounceTime]="2000">自定義時間執行Debounced12 Click</button>
再放一次自定义指令文件代码
import { Directive, EventEmitter, HostListener, OnInit, Output, Input } from '@angular/core';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { Subscription } from 'rxjs';
@Directive({
selector: '[appDebounceClick]'
})
export class DebounceClickDirective implements OnInit {
@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);
}
}
好了,完成了~~ 三种情况自己看吧~