Angular2 – Material Autocomplete and remote filtering data


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



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!

稿源:Yet Another IT Blog (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Angular2 – Material Autocomplete and remote filtering data

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录