Angular 7/6 Material Autocomplete Example with Remote/ Server Side Results

We have already discussed the basic usage and implementation of Angular Material Autocomplete Component in an Angular Application in our previous post here.

Autocomplete is a very popular behavior used in many application to easy user form filling experience by providing some already built strings to fast data entry. Autocomplete is very similar to Input fields with addition to some Items showing up when the user focuses on that Input.

Sometimes we may need to show some results from the server side as per a request made by the user. For example, there are two fields for State and City. A user will first select a State, then City list will load in other Input from the server side according to state selected, as we may have thousands of cities from 12-15 states Right?

In this post, we will add Angular Autocomplete with Debounce feature which will fetch results from server/API response. Here we will also use HttpClient service of Angular to make Get request to IMDB movies API for demonstration.

You can check my previous post to know more on adding Angular Material in Angular project.

Autocomplete with server-side responses will also use the debounceTime method of Rxjs for optimized API calls for results.


Implement Server Side Autocomplete

Let’s add HttpClientModule and some other Angular material Modules which will be used in our demo.

Open App’s main module file app.module.ts then replace below code.

To make server HTTP calls add HttpClientModule, for autocomplete import MatInputModule & MatAutocompleteModule.

We have FormsModule with ReactiveFormsModule so that we can easily bind RxJS debounceTime and also get input value.

Add Autocomplete template

In app.component.html file replace below template to show Input Field with Autocomplete.

In app.component.ts file replace following code to make server calls to populate Autocomplete results using OMDB free API.

debounceTime checks if keypress intervel is less then time provided, then cancels the further events.

tap and finalize operators are used to handle events before the server call and after response.

switchMap is mostly similar to mergeMap but it is used here as it cancels previous request event if the response is not received yet. But mergeMap waits for a previous response then make next call so this behavior is not required here.

Also check: How to add Angular Material Loaders and Spinners in Angular App

That’s it now you have a working Angular Material Autocomplete fetching server-side responses as user types in having RxJS DebounceTime which will only hit API HTTP call when the user stops typing.


Leave a Reply

Notify of