- 首先, 引入依赖, 并创建指令
import { Directive, ElementRef, Input } from '@angular/core';
import { fromEvent, Observable } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Directive({
selector: '[onDebounceInput]'
})
export class OnDebounceInput {
@Input('onDebounceInput') handler: (e?) => void = () => {};
input$: Observable<any>;
constructor(el: ElementRef) {}
}
- 在构造函数中取得dom元素,并创建observable
constructor(el: ElementRef) {
this.input$ = fromEvent(el.nativeElement, 'input').pipe(debounceTime(300));
this.input$.subscribe((e) => this.handler(e));
}
- 使用
<input
nz-input
[(ngModel)]="text"
[onDebounceInput]="handleFilterChange"
/>
handleFilterChange(e) {
this.getList();
}