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

2019-05-08  本文已影响0人  铁了个铁
  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();
}
上一篇 下一篇

猜你喜欢

热点阅读