Angular 5 – Custom filters in data tables with firestore

Hi Friends,

Hope you are all well. This is part 3 of my Material Data tables with Angular 5 and Firestore series. Part 1 and Part 2 can be found here and here. In this post let’s see how to filter data in our data tables.

I presume you already have a copy of the code we have done so far. If not, you could grab it from here.

Let’s begin.

 

Code for this post is available – here.

Now setting custom filters is pretty much easy on a data table. A data table takes input from an observable through the dataSource attribute. If you query for data based on specific criteria and pass the resultant observable as the dataSource input then voila, you get the datatable with only the values specific to the filters you set.

Now in our code open up app.component.html and add a couple of select fields that will enable us to specify some criteria.

Note that I have added one extra input field for specifying a value which will serve as the boundary for filtering and a couple of buttons; one for setting filters and the other for clearing them.

Don’t forget to add the MatSelectModule import in app.module.ts file.

Now open up app.component.ts file and modify the code as shown below.

Though the code looks a bit lengthy, I have just added a couple of functions to set the filters and to reset the filters. That’s it. I have also added a new class called FilteredDataSource which will return an observable in the connect() method so that the datatable gets it’s input.

Now open up student.service.ts file and add the below code.

I have just added a filterData() function. It queries for the rows based on the specified criteria in the collection and returns an observable.

This is the line that does all the querying for us. The customfilters object is sent from the app.component.ts file. As simple as that.

Now simply run the code and you could see our app in action.. :)

That’s it guys. You could similarly create filters for whichever column you want. You could also chain where queries in firestore which means you could simply add more than one criteria in the same column.

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

Thanks for reading. Peace.. :)

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

    Thanks for article! Absolutly helpful!

  • An Karthik

    Awesome article

  • Nicolas Contreras V

    Hello, thanks for this post! Really helpfull for me :)

    I’m having a problem retreiving data from firestore with the query option .where() . Data is coming empty every time I call .where( … ) option. Any idea if some updates have come to AngularFire2?