Angular 5 – Material Data tables with Firestore

Hi Friends,

Hope you are all well. In this post let’s talk about creating data tables with Angular Material 2 and populating them with data from Firestore.

Let’s begin.

A screencast of this post.

Code for this post is available – here.

Scaffold out a project using the CLI and open up environment.ts file (inside the src/environments directory) and modify it as shown below.

(Please install firebase and angularfire2 before doing this)

Now let’s install angular material 2. Use the below commands to install.

Open up styles.css and add the below import.

Now generate a new service, which we’ll be using to pull data from firestore using the below command.

Open up app.module.ts file and modify it as shown below.

Nothing new.. We are just importing all our modules that we installed/generated.

Let’s move on. Open up app.component.html file and add the below code .

We are just creating a form with three fields which will enable us to add a document to our students collection.

Our collection would look something like this.


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

We simply have two methods to add a document to our collection and to pull documents from the collection. The getStudents() method will return an observable.

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

Let’s break this down.

  1. The addStudent() method is to add a student to our collection.
  2. The displayedColumns array is the one that corresponds to the matHeaderDef. The values given in this array will serve as the Column headers in our datatable.
  3. The data table itself will take an observable as input. This observable will be stream of values that we get from the collection, with each value corresponding to a document.
  4. The StudentDataSource is a derived class which extends the DataSource class and provides the connect() and disconnect() method which our data table will use. Here notice that I am passing the observable which I got from the student service in the connect method().

That’s it. Now try running the app. You should see a screen as shown below.


In our next post we’ll see how to sort and filter data in a data table.

Hope this helped you guys. If you found this helpful; kindly share it with someone and help them too. Donate to keep this site alive.

Thanks for reading guys. Peace.. :)

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