debounce to get a value input in angular2

Viewed 24714

I want to get a value from an input text after a few time (many millisecond or seconds) in angular 2, when a custom write an input but without waiting him to click a button.

I have tried this, but even when I use debounceTime, value is send in every keypress.

I try to learn about debounce and observable and this is what I understand, Can anyone please help me to fix my code:

component.html:

<md-card-title *ngIf="!edit">{{card.title}}</md-card-title>
 <input *ngIf="edit" type="text" [(ngModel)]="card.title" (ngModelChange)='rename()'/>

component.ts

newTitle: string;
modelChanged: Subject < string > = new Subject < string > ();

constructor()
this.modelChanged
  .debounceTime(500) //before emitting last event
  .distinctUntilChanged()
  .subscribe(model => this.newTitle = model);
}

rename(): void {
  this.renameRequest.emit(this.newTitle);
}
2 Answers

Angular 12.2 + RxJS + lodash

If you're using lodash. $ npm i --save lodash

<input (keyup)="debouncedSearch($event)"/> 
import { debounce } from 'lodash';

...

  debouncedSearch = debounce(
        (event) => this.search(event.target.value),
        400
  )

  search(query: string){
    console.log(query)
  }

...
  <input (keyup)="debouncedSearch()" [(ngModel)]="theInput" /> 

Version with local model

If you have a local var to bind to, you can also do this:

It's more readable and you can set your var in ngOnInit or wherever you need to.

import { debounce } from 'lodash';

...

  theInput: string = ''

  debouncedSearch = debounce(this.search, 400)

  search(){
    console.log(this.theInput)
  }

...
Related