2017-07-14 81 views
0

我正在嘗試創建類似isTyping或不是,因此我必須檢測用戶停止鍵入的時間多少爲3秒,因此我可以做我的東西,當他打字時我都已檢測到使用這個:檢測用戶是否停止鍵入Angular 2

 ngOnChanges(searchValue: string) { 
    if (!this.searchChangeObserver) { 
     Observable.create(observer => { 
     this.searchChangeObserver = observer; 
     }).debounceTime(3000) 
     .subscribe((data) => { 
      if (data) { 
      typingStuff(); 
      } 
      else { 
      notTypingStuff(); 
      } 
     }); 
     this.searchChangeObserver.next(searchValue); 
    } 
    } 
} 

所以現在我必須檢測當用戶停止鍵入做notTypingStuff();

有沒有簡單的方法來做到這一點?

編輯

我也是用這個:

constructor(){ 
    this.modelChanged 
     .debounceTime(300) 
     .subscribe((data) => { 
     if (data) { 
      typingStuff(); 
     } 
     else { 
      notTypingStuff(); 
     } 
     }); 
} 

但是,當用戶停止在3秒內輸入做notTypingStuff()也應該知道..

+0

它會是這樣的:http://jsfiddle.net/francescov/FYkYE/在Angular 2? – Stuart2041

+0

如何使用ngModel及其方法ng-dirty和ng-pristine?你可以在Angular的文檔中閱讀它:https://angular.io/guide/forms#track-control-state-and-validity-with-ngmodel – Haseoh

+0

@Haseoh看起來不錯,你能用一個例子發表一個答案嗎? :) – Stuart2041

回答

0

我會訪問用戶輸入的元素上的(keyup)事件,並檢查事件發生後的時間是否大於等於3s。

+0

是的,但事情是,每次我輸入我必須做一個API調用,如果我想刪除文本,它也會調用API,因爲返回也是一個關鍵.... – Stuart2041

1

對於不打字的東西你可以從輸入事件創建一個可觀察到的,並設置debaunce時間:

HTML:

<input #yourElement [(ngModel)]="yourVar"/> 

組件:

@ViewChild('yourElement') yourElement: ElementRef; 

ngAfterViewInit() { 
    Observable.fromEvent(this.yourElement.nativeElement, 'input') 
     .map((event: Event) => (<HTMLInputElement>event.target).value) 
     .debounceTime(3000) 
     .distinctUntilChanged() 
     .subscribe(data => notTypingStuff()); 
} 

這樣,你的方法只有在輸入被修改後,換句話說,在用戶停止輸入後纔會執行3000次。

+0

不錯,但我怎麼能重置當前debounceTime當用戶重新打字時? –