DEV Community

Cover image for How to create an input search with debounce using Rxjs on Angular
Diogo Machado
Diogo Machado

Posted on

How to create an input search with debounce using Rxjs on Angular

Sometimes we need to create features like a search component that calls the API to return a search based on a string typed. The problem is we should prevent the application from calling the API many times because the user can type a lot fast and it is a problem.

Many developers would solve it with a library like Lodash, forgetting that it is super easy to solve it with Rxjs, the library included on the framework Angular.

In this example, I will focus on resolution with debounce using a simple component and input.

<input 
 type="text" 
 [ngModel]="search" 
 (ngModelChange)="handleSearch($event)" 
 placeholder="Quick Search">
Enter fullscreen mode Exit fullscreen mode

Using the (ngModelChange) we are able to listen to any change on the model and get the last value, using standalone components we need to import FormsModuleas well.

@Component({
  selector: 'app-root',
  standalone: true,
  template: `<input type="text" [ngModel]="search" (ngModelChange)="handleSearch($event)" placeholder="Quick Search">`,
  imports: [FormsModule],
})
Enter fullscreen mode Exit fullscreen mode

Now all you need is a bit of code:

1) Declare the search variable:

search = '';
Enter fullscreen mode Exit fullscreen mode

2) Initialize a BehavierSubject:

 searchSubject = new BehaviorSubject<string>('');
Enter fullscreen mode Exit fullscreen mode

3) Sends the value to the Subject using ngModelChange:

handleSearch(search: string) {
  this.searchSubject.next(search);
}
Enter fullscreen mode Exit fullscreen mode

4) Subscribe the Subject:

constructor() {
    this.searchSubject
    .pipe(debounceTime(550))
    .subscribe((search) => {
      console.log('Searching', search);
    });
}
Enter fullscreen mode Exit fullscreen mode

Final results 🙌

Screen Stackblitz showing the example code

Demo application

Top comments (0)