之前,我們介紹過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 的分享;