Angular
Step by step tutorial for using Angular Material in an Angular 7 app focusing on MatTable setup, data binding, and adding pagination, sorting and filtering.
Angular Material Table With Paging, Sorting And Filtering ZeptoBook
Wireframe overlay treatment: cyan-tinted annotation over matte navy field.
Rating: 4.7 / 5
Signal strength measured across clarity, contrast, and geometry consistency.

Angular

Angular Material is a collection of Material Design components for an Angular app. You can apply Material Design by using these components very easily. Angular Material became very easy with the release of Angular 6. Here, we will work on Angular Material with Angular 7.

Here is the link to Angular Material https:material.angular.io

Angular Material Table mat table

In this blog, we are going to learn about Angular Material Table, that is, mat table. The mat table provides a Material Design styled data table that can be used to display rows of data.

Setting Up The Angular 7 Project

we are going to use Angular 7 project to work with Angular Material Table component. If you are still working on Angular 6, and wants to upgrade your Angular CLI to Angular 7, here is the below link to upgrade from Angular 6 to Angular 7.

Update Angular 6 to Angular 7 version

Also, here is the link to create your first app in Angular 7 as well.

Creating your first app in Angular 7

Lets create our Angular 7 Material app using this command.

ng new angularmat

In this example, angularmat is our project name. A new project folder is created, the Angular project template is downloaded and the needed dependencies are installed. Once everything is set up, and now you are ready to run your application by using this command.

ng serve open

Now, its a time to add Angular Material dependencies in our project.

1. Install Angular Material Angular CDK And Angular Animations To Angular Project

You can use the npm command to install Angular Material Angular CDK and Angular Animations to your project.

npm install save angularmaterial angularcdk angularanimations

2. Configure Animation By Importing BrowserAnimationsModule

Once the above packages have been installed in your app the next step is to configure the animation by importing BrowserAnimationsModule in your app.modulets file.

import BrowserAnimationsModulefrom angularplatform browseranimations NgModule imports BrowserAnimationsModule export class AppModule

3. Importing Angular Material Theme

It is required to importing the Angular Material theme in your project. Open your projects file styles.css and add this line.

import angularmaterialprebuilt themesindigo pink.css

4. Adding Angular Material Icons optional

You can use Angular Material Icons in your project. Here is the official link of Material Design Icons. Open your index.html and add this link in this file.

5. Import Angular Material Table MatTableModule

Now in order to use Angular Material Table you have to import the MatTableModule in your module file. Open the app.modulets file and import this statement.

import MatTableModulefrom angularmaterialtable NgModule imports MatTableModule export class AppModule

6. Create Mat Table Data For Display

To display data in our mat table lets first create our sample data interface and populate the data. I am going to create an interface EmployeeData having the following properties. Adding the array of employees names and their favorite colors as well.

Adding the array constants of employees names and their favorite colors. The getEmployees function will return the full employee data to display.

export interface EmployeeData Id string EmpName string Color string Hours number const FAVORITE_COLORS string gray black navy blue teal green purple fuchsia lime olive aqua yellow orange red maroon const EMP_NAMES string Robert Jing Jo Thomas Peter Sam Jack Charlie Maria Julia Albert Arthur James Simran Levi Violet Arthur Mia Thomas Elizabeth function getEmployeesid number EmployeeData const name EMP_NAMESMath.roundMath.random EMP_NAMES.length 1 EMP_NAMESMath.roundMath.random EMP_NAMES.length 1 .charAt0 . return Id id.toString EmpName name Color FAVORITE_COLORSMath.roundMath.random FAVORITE_COLORS.length 1 Hours 8

7. Bind Data to Mat Table

Once you have setup the data for mat table we are now good to go to bind it with mat table. Lets import MatTableDataSource in our app.componentts file.

import MatTableDataSource from angularmaterial

Fill the displayedColumns array with the name of columns to be displayed in our table. Also mention the EmployeeData interface as our data source. We have created a emplist properties and assigned the 100 employees to this list. Finally I have passed this emplist to our mat table data source property.

displayedColumns string Id EmpName Color Hours dataSource MatTableDataSourceEmployeeData emplist any constructor this.emplist Array.from length 100 _ k getEmployeesk 1 this.dataSource new MatTableDataSource this.emplist

7.1 Create mat table and bind data

Next step to create our html template to bind these properties to mat table component. Here is the syntax of data binding in our app.componenthtml file.

Write your mat table and bind the dataSource property to it.

table mat table dataSourcedataSource table

This is the simple form of binding data to mat table. The table will take the array and render a row for each object in the data array.

7.2 Creating the column template

After creating our mat table and binding its dataSource next step is to create our column template.

Each column should have a unique column name and it will contain the contents of its header and row cells.

ng container matColumnDefId th mat header cell matHeaderCellDef ID th td mat cell matCellDeflet row row.Id td ng container

In the above sample we have given the unique name Id to our column property matColumnDef. Inside the ng container we have defined mat header cell for displaying the ID header and bind the data using row.Id to mat cell of our template.

So the complete column bindings will be like this

ng container matColumnDefId th mat header cell matHeaderCellDef ID th td mat cell matCellDeflet row row.Id td ng container ng container matColumnDefEmpName th mat header cell matHeaderCellDefEmployee Name th td mat cell matCellDeflet row row.EmpName td ng container ng container matColumnDefColor th mat header cell matHeaderCellDef Color th td mat cell matCellDeflet row row.Color td ng container ng container matColumnDefHours th mat header cell matHeaderCellDefHours th td mat cell matCellDeflet row row.Hours td ng container

7.3 Defining the row template

In the last step we have to define row template where we will tell the table which columns be rendered in the header and data rows. For that purpose we have already created a variable displayedColumn in our component class file.

displayedColumns string Id EmpName Color Hours

Add these two lines at the bottom of your mat table tag to specify which columns we are going to show.

tr mat header row matHeaderRowDefdisplayedColumns tr tr mat row matRowDeflet row columns displayedColumns tr

so the complete html template will be like this.

div table mat table dataSourcedataSource ng container matColumnDefId th mat header cell matHeaderCellDef ID th td mat cell matCellDeflet row row.Id td ng container ng container matColumnDefEmpName th mat header cell matHeaderCellDefEmployee Name th td mat cell matCellDeflet row row.EmpName td ng container ng container matColumnDefColor th mat header cell matHeaderCellDef Color th td mat cell matCellDeflet row row.Color td ng container ng container matColumnDefHours th mat header cell matHeaderCellDefHours th td mat cell matCellDeflet row row.Hours td ng container tr mat header row matHeaderRowDefdisplayedColumns tr tr mat row matRowDeflet row columns displayedColumns tr table div

Now it is the time to run your app and see the data in the mat table. Run ng serve open in your terminal.

Showing 100 of rows in mat table

Till now we have implemented our basic mat table. Now lets move to the next feature of mat table that is pagination.

8. Mat Table Pagination

mat paginator is used to provide pagination with the mat table. Each paginator requires two basic things

The number of items per page default is 50

Total number of items being paged

The paginator displays a dropdown of page sizes for the user to choose from. The options for this dropdown can be set via pageSizeOptions

The current pageSize will always appear in the dropdown even if it is not included in pageSizeOptions.

To implement the pagination first of all import the MatPaginatorModule in your app.modulets file. Add MatPaginatorModule in imports array as well.

import MatTableModulefrom angularmaterialtable import MatPaginatorModule from angularmaterial NgModule imports MatTableModule MatPaginatorModule export class AppModule

Lets implement the MatPaginator in our app.componentts file.

import Component OnInit ViewChild from angularcore import MatTableDataSource MatPaginator from angularmaterial export class AppComponent implements OnInit ViewChildMatPaginator paginator MatPaginator ngOnInit this.dataSource.paginator this.paginator

Also place mat paginator element on app.componenthtml file as well.

mat paginator pageSizeOptions5 10 25 100 mat paginator

Let me explain you about this pagination control. First of all we imported ViewChild and MatPaginator in our component class file. Then we accessed our MatPaginator control using ViewChildMatPaginator and in ngOnInit life cycle hook we assigned this paginator to our datasource paginator property.

Dont forget to put mat paginator with pageSizeOptions attribute on component html file.

Mat table with Pagination

9. Mat Table Sorting

In this step we are going to implement mat table sorting feature. Like other modules we have to first import MatSortModule in our app.modulets file. Add this MatSortModule in import array as well.

import MatTableModulefrom angularmaterialtable import MatPaginatorModule from angularmaterial import MatSortModulefrom angularmaterialsort NgModule imports MatTableModule MatPaginatorModule MatSortModule export class AppModule

Now go to the app.componenthtml file add matSort to table mat table tag. Also we have to add mat sort header to each column. Add mat sort header to th mat header cell of each column.

div table mat table dataSourcedataSource matSort ng container matColumnDefId th mat header cell matHeaderCellDef mat sort header ID th td mat cell matCellDeflet row row.Id td ng container table mat paginator pageSizeOptions5 10 25 100 mat paginator div

Now move to app.componentts file and implement the sorting over there as well.

import Component OnInit ViewChild from angularcore import MatTableDataSource MatPaginator MatSort from angularmaterial export class AppComponent implements OnInit ViewChildMatSort sort MatSort ngOnInit this.dataSource.sort this.sort

Let me explain this first of all we have imported MatSort in our component class file. Then using ViewChildMatSort we accessed our MatSort component and finally we assigned sort to datasource sort property.

Mat table sorting

Look at the table headers you will header a sort arrow on each on mouse hover. In this picture I sorted Employee Name and you can an arrow on this column as well.

10. Mat Table Filtering

In this last point I am going to show you how to filter your mat table.

First of all import these statement in your app.modulets file and add MatFormFieldModule and MatInputModule in imports array.

import MatFormFieldModulefrom angularmaterialformfield import MatInputModulefrom angularmaterialinput

After importing above modules let place matInput field on our app.componenthtml file.

app.component.html

h3Filterh3 mat form field input matInput keyupapplyFilterevent.target.value placeholderFilter input mat form field

I have bind an event applyFilter on matInput keyup event which will filter our data. Lets create our applyFilter function in the component class file.

app.component.ts

applyFilterfilterValue string this.dataSource.filter filterValue.trim.toLowerCase if this.dataSource.paginator this.dataSource.paginator.firstPage

Mat table filtering

The applyFilter is very simple. It will use the datasource.filter property to filter the mat table and if we used paginator it will set the first page as result.

Download

You can download the complete project from Github.

Download Project Files

Summary

In this tutorial we learned about how to install Angular Material in our Angular app. Then how we can use Mat Table to display the tabular data. I also demonstrate common features of any data grid like Pagination Sorting and Filtering.

Further Reading

ng template ng container And ngTemplateOutlet In Angular

Spread Operator In TypeScript

Learn About Observables Observers And Operators of RxJS Angular

Next
Contacts: Request review
COMMENTS
No comments yet. This block is reserved for a future threaded system.
Return to top