Detect if user stop typing Angular 2

Viewed 16115

I'm trying to create something like isTyping or not, so I have to detect when user stop type more or less 3 seconds, so I can do my stuff, I allready detected when he's typing using this :

     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);
    }
  }
}

So now I have to detect when user stops typing to do the notTypingStuff();

Is there a simple way to do it?

EDIT

I'm also using this :

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

But should know when user stops to type in 3 seconds to do the notTypingStuff() as well..

3 Answers

For the not typing stuff you could create an observable from the input event and set the debaunce time:

HTML:

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

Component:

@ViewChild('yourElement') yourElement: ElementRef;

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

This way your method will only be executed 3000 after the input is modified, or in other words after the user stops typing.

EDIT: Angular 9 w/ RxJS 6.5.4

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

Angular Version 6.

HTML:

<input matInput type="text" (keyup)="searchInterest()" [(ngModel)]="keyword" [matAutocomplete]="auto">

COMPONENT:

public searchInterest() {
    let wordSearch = this.keyword;
    setTimeout(() => {
        if (wordSearch == this.keyword) {
            if (this.keyword) {
                //função que irá retornar sua lista de objetos
            }else{
                //code here
            }
        }
    }, 2000);
}
Related