Thursday, 7 December 2017

Angular2 - Material Autocomplete and remote filtering data

Problem:

The last couple of days I was struggling to get the Angular2 Material Autocomplete to work with our api. I wanted the autocomplete options remotely filtered. Several solutions I found, worked with a (cached) list of items. So all items were first retrieved and after that, those were filtered by the autocomplete. This is ok if the full list is a short list, but not for long(er) lists.
Well, after searching and trying a lot, and for a long time (also together with my colleague Frank den Outer, special thanks to him!) and struggling with promises and observables, we found the solution and it is actually really simple (at least, it looks like that).

The data is coming from an server api and is accessed by the function getCompanies(search: string) from a company.service.ts (which is injected in the user component). This function returns an Observable.

Solution


On the user.component.html I used:












On the related user.component.ts, you the following pieces of code:



The 'debounceTime(300)' is used to prevent a api-call on each keyup event.
In our case, if no value is entered in the input box, the api returns the first 20 entries of the list of companies.
The main difference with other solutions (where a (cached) list on client side is used) is the .subscribe() part. In other solutions you will find a .map call, something like this:


where allCompanies is a fetched list with all companies. This .map function will not respond correctly with the customSearchFunction if the result is retrieved directly from a api.

But I really prefer the 'subscribe' solution, because you get directly your data filtered from you api and you don't need to preload all data and store it local. And it is less code as well ;)

Happy programming!

No comments: