1、创建指令
// 以下命令会创建DebounceDirective指令并自动添加到AppModule
ng g directive directive/debounce
2、相关代码
// app.component.html
<input appDebounce [debounceTime]='2000' (debounceKeyup)="testDebounceKeyup($event)" />
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.styl']
})
export class AppComponent {
testDebounceKeyup(event: any) {
console.log("Keyup被节流了!");
}
}
// debounce.directive.ts
import { Directive, EventEmitter, HostListener, Input, Output, OnInit, OnDestroy } from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { Subject, Subscription } from 'rxjs/';
@Directive({
selector: '[appDebounce]'
})
export class DebounceDirective implements OnInit, OnDestroy {
private operates = new Subject<any>();
@Input()
private debounceTime = 1000;
@Output()
private debounceKeyup = new EventEmitter();
private keyupScription: Subscription;
constructor() { }
ngOnInit() {
this.keyupScription = this.operates
.pipe(debounceTime(this.debounceTime))
.subscribe(e => this.debounceKeyup.emit(e));
}
@HostListener('keyup', ['$event'])
keyupEvent(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
this.operates.next(event);
console.log("我被输入了!");
}
ngOnDestroy() {
this.keyupScription.unsubscribe();
}
}