Angular Material Table: A  Complete Guide with Best Example

Angular Material Table: A Complete Guide with Best Example

Angular Material Table Overview

The Angular Material library offers the robust and adaptable Angular Material Table component as a means of presenting tabular data in a tidy and contemporary manner. It makes it simple to design feature-rich and user-friendly tables with a broad range of functions including sorting, filtering, pagination, and more.

We’ll look at several Angular Material Table kinds, give detailed examples, and talk about how to make them editable in this blog article. Now let’s get started!

A library of UI components for Angular developers is called Angular Material. It provides a large selection of components, such as tables, to make it easy and quick for you to create cutting-edge, responsive web apps. We’ll dive into Angular Material tables in this blog article, covering various table kinds, creating and customizing them, and implementing advanced features like editing capabilities.

You ought to know how to use Angular Material tables by the time you finish reading this guide. Now let’s get started!

Angular Material Tables: Why Use Them?

  • Simple Configuration: You may easily design visually stunning and powerful tables with no effort.
  • Rich in features: Sorting, filtering, and pagination are supported by Angular Material tables right out of the box.
  • Because of their responsive design, these tables work well on all types of screens and provide a wonderful user experience.
  • Customizable: You can add buttons, change the columns, and do a lot more to make the tables exactly what you need.

Setting Up Angular Material in Your Project

Before we start creating tables, you need to set up Angular Material in your project. Follow these steps:

Install Angular Material:

ng add @angular/material

Import the Material Modules: In your app.module.ts, import the necessary Angular Material modules.

import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
imports: [
MatTableModule,
MatPaginatorModule,
MatSortModule,
MatInputModule,
MatButtonModule,
MatIconModule,
],
})
export class AppModule { }

Include Angular Material Theme: In your styles.css or styles.scss, include one of the Angular Material themes.

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Creating a Basic Angular Material Table

Let’s start with a simple example. We will create a basic table that displays a list of users.

Step-by-Step Example

Create a Component: Generate a new component for your table.

ng generate component user-table

Define the Data Model: In user-table.component.ts, define a simple data model for users.

export interface User {
id: number;
name: string;
email: string;
age: number;
}

const USER_DATA: User[] = [
{ id: 1, name: 'John Doe', email: 'john@example.com', age: 25 },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', age: 30 },
{ id: 3, name: 'Sam Johnson', email: 'sam@example.com', age: 22 },
];

Configure the Table: In user-table.component.ts, set up the table data source and displayed columns.

import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

@Component({
selector: 'app-user-table',
templateUrl: './user-table.component.html',
styleUrls: ['./user-table.component.css']
})
export class UserTableComponent {
displayedColumns: string[] = ['id', 'name', 'email', 'age'];
dataSource = new MatTableDataSource(USER_DATA);
}

Create the Table Template: In user-table.component.html, create the table structure.

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- ID Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> ID </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>

<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>

<!-- Email Column -->
<ng-container matColumnDef="email">
<th mat-header-cell *matHeaderCellDef> Email </th>
<td mat-cell *matCellDef="let element"> {{element.email}} </td>
</ng-container>

<!-- Age Column -->
<ng-container matColumnDef="age">
<th mat-header-cell *matHeaderCellDef> Age </th>
<td mat-cell *matCellDef="let element"> {{element.age}} </td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Types of Angular Material Tables:

Basic Table

A basic table is the simplest form of an Angular Material Table. It displays data in a tabular format without any additional features. Here’s an example:

<table mat-table [dataSource]="dataSource">
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef>No.</th>
<td mat-cell *matCellDef="let element">{{ element.position }}</td>
</ng-container>

<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let element">{{ element.name }}</td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>

In this example, we define the columns using ng-container elements with the matColumnDef directive. The *matHeaderCellDef and *matCellDef directives are used to define the header and data cells for each column, respectively. Finally, we specify the columns to be displayed using the displayedColumns array.

Table with Sorting

Angular Material Table provides built-in support for sorting. To enable sorting, you need to add the matSort directive to the table and the mat-sort-header directive to the header cells you want to be sortable. Here’s an example:

<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef mat-sort-header>No.</th>
<td mat-cell *matCellDef="let element">{{ element.position }}</td>
</ng-container>

<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
<td mat-cell *matCellDef="let element">{{ element.name }}</td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>

In this example, we added the matSort directive to the mat-table and the mat-sort-header directive to the header cells we want to be sortable (position and name). When the user clicks on a sortable header, the table will automatically sort the data based on the selected column.

Table with Pagination

Pagination is another common feature of Angular Material Tables. To enable pagination, you need to add the mat-paginator component to your table. Here’s an example:

<table mat-table [dataSource]="dataSource">
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef>No.</th>
<td mat-cell *matCellDef="let element">{{ element.position }}</td>
</ng-container>

<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let element">{{ element.name }}</td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>

<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>

In this example, we added the mat-paginator component after the table. The [pageSizeOptions] input binds the available page size options, and the showFirstLastButtons attribute displays buttons to navigate to the first and last pages.

Editable Table

Making an Angular Material Table editable allows users to modify the data directly within the table. Here’s an example of how to create an editable table:

<table mat-table [dataSource]="dataSource">
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef>No.</th>
<td mat-cell *matCellDef="let element">{{ element.position }}</td>
</ng-container>

<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let element">
<mat-form-field appearance="fill">
<input matInput [(ngModel)]="element.name" />
</mat-form-field>
</td>
</ng-container>

<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Actions</th>
<td mat-cell *matCellDef="let element">
<button mat-icon-button (click)="saveChanges(element)">
<mat-icon>save</mat-icon>
</button>
</td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>

In this example, we added a new column called “Actions” that contains a save button. We used the mat-form-field and matInput components to make the “Name” column editable. The [(ngModel)] directive binds the input value to the corresponding element in the data source. When the user clicks the save button, the saveChanges function is called, allowing you to handle the data update.

Adding Pagination and Sorting

To enhance our table, let’s add pagination and sorting functionalities.

Update Component Class: In user-table.component.ts, import and configure MatPaginator and MatSort.

import { ViewChild, AfterViewInit } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

export class UserTableComponent implements AfterViewInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  displayedColumns: string[] = ['id', 'name', 'email', 'age'];
  dataSource = new MatTableDataSource(USER_DATA);

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
}

Update Template: Add the paginator and sort directives to the template.

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<!-- ... (existing columns) ... -->

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>

Editing an Angular Material Table

Now, let’s add editing capabilities to our table. We will allow users to edit the name and email fields.

Step-by-Step Example for Editing

Add Edit Button to Each Row: Update the displayedColumns and the table template to include an edit button.

displayedColumns: string[] = ['id', 'name', 'email', 'age', 'actions'];
<!-- Actions Column -->
<ng-container matColumnDef="actions">
  <th mat-header-cell *matHeaderCellDef> Actions </th>
  <td mat-cell *matCellDef="let element">
    <button mat-icon-button (click)="editUser(element)">
      <mat-icon>edit</mat-icon>
    </button>
  </td>
</ng-container>

Create an Edit Form: Add a form to edit user details. Use Angular Material Dialog for the form.

ng generate component edit-user-dialog

In edit-user-dialog.component.ts:

import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Inject } from '@angular/core';

export class EditUserDialogComponent {
constructor(
public dialogRef: MatDialogRef<EditUserDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: User
) {}

onCancel(): void {
this.dialogRef.close();
}
}

In edit-user-dialog.component.html:

<h1 mat-dialog-title>Edit User</h1>
<div mat-dialog-content>
<mat-form-field>
<mat-label>Name</mat-label>
<input matInput [(ngModel)]="data.name">
</mat-form-field>
<mat-form-field>
<mat-label>Email</mat-label>
<input matInput [(ngModel)]="data.email">
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onCancel()">Cancel</button>
<button mat-button [mat-dialog-close]="data">Save</button>
</div>

Open Edit Dialog: In user-table.component.ts, add a method to open the dialog.

import { MatDialog } from '@angular/material/dialog';
import { EditUserDialogComponent } from '../edit-user-dialog/edit-user-dialog.component';

constructor(public dialog: MatDialog) {}

editUser(user: User): void {
const dialogRef = this.dialog.open(EditUserDialogComponent, {
width: '250px',
data: { ...user }
});

dialogRef.afterClosed().subscribe(result => {
if (result) {
const index = this.dataSource.data.findIndex(u => u.id === user.id);
if (index !== -1) {
this.dataSource.data[index] = result;
this.dataSource = new MatTableDataSource(this.dataSource.data);
}
}
});
}

Using the strong and adaptable Angular Material Table component, you can build feature-rich and intuitive tables for your Angular apps. You may simply construct tables with sorting, filtering, pagination, and even editability by utilizing its built-in features and customization choices.

Always remember to adhere to recommended practices, which include importing the required modules, identifying the data source accurately, and utilizing the relevant directives. You can design dynamic and interesting user interfaces for your applications if you have a firm grasp of Angular Material Table.

Other : Angular Material : A Comprehensive Guide With Example

          Leave a Reply

          Your email address will not be published. Required fields are marked *