Bind data to MatTable Angular Material

Angular Material MatTable is very easy to use, populate data in a MatTable is simply easy to use, Angular material also provides great flexibility to apply multiple actions on data such as sorting, filtering, pagination.

Let's start with some real stuf and check beauty of Angular Material MatTable.

Simply Follow  below steps to populate data in a MatTable and modify as per your requirement.

Create a model

export class Employee { id: number; name: string; } 

Create a component, let's name it EmployeeComponent and use below code


export class EmployeeComponent implements OnInit {
  displayedColumns: string[] = ['id', 'name']; // cloumns which you need to display in table as table header
  dataSource = new MatTableDataSource(); // create a datasource
  constructor(){}

  ngOnInit(): void {
    this.getDataFromService();
  }

  getDataFromService(): void {
    this.serviceName.getDataFromService()
    .subscribe(data => {
      this.dataSource.data = data;      
    });    
  }
}

Let's Add View Part


<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </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>

I hope it can help you..., Please write down below to improve this article or have any query.

Enjoy Coding :)

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *
Phone