This article talks about an efficient way to implement auto-complete feature using Angular concepts. The key components used in this demonstration are as follows:
- Angular Material (v12) Autocomplete module.
- RxJS for action and data binding.
- Angular in-memory-web-api for REST services (Refer to in-memory-web-api).
Let us now see how we go about it:
The front-end consists of an angular autocomplete module. The input event taps the user's keystrokes and emits a new value into an action subject.
Each key-stroke emits a new value into an action subject declared in the
BehaviorSubject starts with an empty string. The
action$ is an
observable built out of this subject.
Every time a new value is emitted into the action stream, it returns an observable from the http
GET request. Since this is a higher-order observable (i.e., an observable returning an observable), we make use of one of the higher order functions like
switchMap (and not other higher order functions like
mergeMap)? The reason is:
switchMap unsubscribes from the previous observable once a new value is emitted by the parent observable.
What this means is - as soon as the user types in another letter or removes a letter, there is simply no need to subscribe and execute the rest call for the previous values. The user is only interested to see the results of the search according to his/her current input. And
switchMap does this automatically, and thus gets rid of unwanted rest calls.
We can also get additional control on when to fire the rest service depending on the length of the user's input. For example, in this demo, I fire the rest call only when the user has entered at least 2 characters. If not, then I return an observable of empty array (using
@angular/cli - 12.1.0
@angular/material - 12.1.1