使用rxjs为input添加一个angular节流input事件指令

  1. 首先, 引入依赖, 并创建指令
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) {}
}
  1. 在构造函数中取得dom元素,并创建observable
    constructor(el: ElementRef) {
        this.input$ = fromEvent(el.nativeElement, 'input').pipe(debounceTime(300));
        this.input$.subscribe((e) => this.handler(e));
    }
  1. 使用
<input
  nz-input
  [(ngModel)]="text"
  [onDebounceInput]="handleFilterChange"
/>
handleFilterChange(e) {
  this.getList();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容