Angular 5 + Firestore – Sorting in data tables

Hi Friends,

Hope you are all well. This post is a sequel to my previous post on creating data tables using the Angular Material 2 framework with data from Firestore. In this post let’s see how to sort the columns in ascending or descending order in our data table.

Let’s begin.

A screencast of this post.


Code for this post is available here.

I presume you all have a copy of the repo we created in our previous post. If not kindly clone it from here.

Now that you have a copy of the code, open up app.module.ts and add the following imports into it

And add them to the imports array and providers array as well.

Now open up app.component.html and let’s add a directive to indicated that we wish to perform sorting on the table.

Note that we have added mat-sort-header to each mat-header-cell tag.

Now open up app.component.ts and modify it as shown below.

Yeah, yeah; I know there’s too much code. Let’s break this down. Shall we ?

  1. We have created a new class that uses the getStudents() method in student service to get the list of students and then pass it on to a BehaviorSubject. If you wish to know more about how to use BehaviorSubjects kindly click here.
  2. We have created an instance of this class (studentDatabase class) and then we are passing on this instance to the DataSource class in OnInit method of the App Component class.
  3. If you notice the dataSource is the one that we are using in app.component.html as input to the data table.
  4. Now look at the connect() method. We are combining both the observable streams and mapping it with the result from the getSortedData() function.
  5. The getSortedData() function is the one that does the actual sorting. Once we have the sorted data this is returned as an Observable which is picked up and given as input to the data table.


Now run the app. Once the data table is created and loaded simply click on the row headers to watch the data in the table being sorted in ascending or descending direction.

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

In our next post, we’ll see how to add custom filters and fetch data into the table accordingly.

Thanks for reading guys. Peace.. : )

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

    thank you! but one question: isn’t it better to do sorting on server side?

  • Bharadwaja

    I am using firebase with your example it is not loading data into the table. In the connect method. If i do return this.studentDB.studentList its loading the data. If not it is not loading the data. On click on sort headers data is being sorted in the background i can see the data sorted in the console but its not loading into the table. Can you tell why?