angular中搜索框指令

之前,我们介绍过angular的请求防抖debounce,可以优化搜索过程。鉴于,输入搜索,在整个项目中,应用会相对频繁,所以,我们可以抽离出来,写成一个指令:

import { Directive, HostListener, ElementRef, Input, Output, EventEmitter } from '@angular/core';
import { Subject, Subscription, Observable } from 'rxjs';

import {debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';

@Directive({
  selector: '[appDebounceInput]'
})
export class DebounceInputDirective {
  searchText$ = new Subject<string>();
  subscription:Subscription

  @Input('time') waitingTime = 500; //等待时间
  @Output() emitTargetValue = new EventEmitter(); //将数据传递出去

  constructor(private _elementRef:ElementRef) { 

  }

  @HostListener('keyup', ['$event']) onKeyDown(ev) {
    ev.preventDefault(); //阻止元素发生默认行为
    ev.stopPropagation() //阻止事件冒泡到父元素
    const value = ev.target.value;
    this.searchText$.next(value);
  }

  ngOnInit(): void {
    this.subscription = this.searchText$.pipe(
      debounceTime(this.waitingTime),
      distinctUntilChanged()
    ).subscribe(val=>{
      this.emitTargetValue.emit(val);
    });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

}

在需要的地方引入:
user-form.component.html

<span>请输入:</span>
<input appDebounceInput time="600" (emitTargetValue)="getInputVal($event)" type="text"/>

user-form.component.ts

  getInputVal(ev){
    //get input value
    console.log(ev);
  }

效果图
完整代码: 完整代码链接
感谢: https://blog.csdn.net/u013013856/article/details/86165298 的分享;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章