美文网首页
使用rxjs为input添加一个angular节流input事件

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

作者: 铁了个铁 | 来源:发表于2019-05-08 10:37 被阅读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();
}

相关文章

网友评论

      本文标题:使用rxjs为input添加一个angular节流input事件

      本文链接:https://www.haomeiwen.com/subject/raariqtx.html