Angular 5 – TypeAheads with data tables.

Hi Friends,

Hope you are all well. This post is a response to many of my viewers asking me to do a typical typeahead which would filter the data table with results pertaining to whatever was typed in rather than setting an all-out filter like we saw in our previous post.

Let’s begin.

A screencast of this post.

 

Code for this post is available –  here

I presume you already have a copy of the code that we made so far. If not then, kindly clone it from here.

First we’ll just go ahead and create a simple text field which will function as our type ahead box.

Open up app.component.html and add the below code.

The app.component.html file would look like as shown below.

Note that I have added the form field below the buttons which I created in the last custom filters. You can add it wherever you want.

Also note that that I have bound the keyup attribute to a function called search(). Let’s go ahead and create that event in app.component.ts

First let’s create two subjects startAt and endAt which we will be using to get the searchTerms.

Now write the code for search().

All we do here is, we check if there is anything typed into the form field and if there is any it’s being sent into the subject’s stream. If not we are simply giving the StudentDataSource instance as the input to our data table.

Now in the ngOnInit() function let’s subscribe to these subjects.

This combineLatest function will take two subjects, BehaviourSubjects or Observables and combine the latest values of these two streams and return an array. I am simply getting these two values and then passing these on to a function called typeAhead() in the student service.

Open student.service.ts and add the below code.

This just returns an observable containing the data that was queried from the collection based on our search term.

Add a TypeAheadDataSource class in your app.component.ts file now as shown below.

Now this will get the observable passed to it and simply pass it on as an input in the connect() function. (Creation of this class is unnecessary as we could simply use the FilteredDataSource class itself, I just did it so that it woud be easier to follow).

Now if we give an instance of this class to the dataSource of the data table then we would obviously get the filtered results as shown below.

Screenshot 2018-01-04 16:25:07

Now we have our TypeAhead working perfectly. Similarly you can do a typeAhead for the other columns in your data table as well.

Hope this helped you guys. If you found this helpful, kindly share it with someone and help them too.

Thanks for reading. Peace.. :)

Liked it? Take a second to support admin on Patreon!