A neat UX pattern is to use an auto-complete component to help select known options.

Let’s say I want to choose a user from a list of registered user stored in a server, or to.. just enter an arbitrary name.

What we’re trying to achieve

We’ll use Angular 6 and Angular Material to get this:

Part 1 —Fetching the options from the server

First let me describe the response from the server we’re dealing with:

{

total: 5

results: [

User(id: 1, name: "Windstorm"),

...

]

}

After we’ve clarified this, let’s move on to the how we populate the auto-complete:

We’re creating a reactive form so we could receive an Observable to watch after changes done to the input.

Next, we’re storing the Observable we get from valueChanges in filteredUsers but only after we also apply to it the search method we have (just a regular data-fetching service), and flatten it so the next value in the pipeline would be the response from the server.

We also use debounceTime since we don’t want to make a request to the server for each single changed letter in the input.

NOTE: We do not subscribe from the observable yet. For that we’ll use an async pipe

Here’s the html to put the auto-complete’s options in place:

The async pipe will now subscribe for us to filteredUsers and we only then access the results value which holds our options.

Here’s the demo

Part 2 — Adding a spinner while options are being retrieved

We just need to add a mat-option to be displayed while loading.

In addition — We use a tap and finalize pipes to decide when to show and hide isLoading

NOTE: The finalize must be used for the search method since the underlying httpClient completes the subscription after 1 emission, while valueChanges never ends, so it won’t hit finalize

Here’s the demo

And, there you go! Cheers :)