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">
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 FormsModule
as well.
@Component({ selector: 'app-root', standalone: true, template: `<input type="text" [ngModel]="search" (ngModelChange)="handleSearch($event)" placeholder="Quick Search">`, imports: [FormsModule], })
Now all you need is a bit of code:
1) Declare the search variable:
search = '';
2) Initialize a BehavierSubject:
searchSubject = new BehaviorSubject<string>('');
3) Sends the value to the Subject using ngModelChange:
handleSearch(search: string) { this.searchSubject.next(search); }
4) Subscribe the Subject:
constructor() { this.searchSubject .pipe(debounceTime(550)) .subscribe((search) => { console.log('Searching', search); }); }
Top comments (0)