Responsive table using Angular Material

In this article, we discuss how to easily implement a responsive table with pagination using Angular Material. Here we have use mat-table, mat-header-cell, mat-cell, mat-row, mat-paginator provides used to display table with pagination. first, we need to install angular material run below code to install


npm i @angular/material
npm i @angular/flex-layout

After installing module lets add a module in our app.module.ts file.

....
import { FlexLayoutModule } from '@angular/flex-layout';
import {MatNativeDateModule, MatRippleModule} from '@angular/material/core';
import {MatPaginatorModule} from '@angular/material/paginator';
import {MatSortModule} from '@angular/material/sort';
import {MatTableModule} from '@angular/material/table';
...
@NgModule({
imports:      [ ..., FlexLayoutModule,MatNativeDateModule,MatRippleModule,MatSortModule,MatPaginatorModule,MatTableModule  ],
....
})



After adding a module in the app.module file we can use it in our component to draw the chart. Let’s create app.component.ts file and add import table module in component file.


import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';

We need to genrate data fro the table to display for that we have created function to genrate table data it may comes from your api form the server.


    // Create 120 users
    const users: UserData[] = [];
    var userdata=[];
    for (let i = 1; i <= 120; i++) { 
    
      userdata.push({"cnt" : i,"name": NAMES[i%15],'progress': Math.round(i/120 *100),'color':COLORS[i%12]});
      
     }

    // Assign the data to the data source for the table to render
    this.dataSource = new MatTableDataSource(userdata);

Display below is the code for the app.component.ts ,app.component.html,app.component.css


/*https://www.eduforbetterment.com/
*/
import { Component, ViewChild } from '@angular/core';
import { SimpleNotificationsComponent } from 'angular2-notifications';
import { NotificationsService } from 'angular2-notifications';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';




@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 10';
  options={
      timeOut: 3000,
      showProgressBar: true,
      pauseOnHover: true,
      clickToClose: true
    };
constructor( private _service: NotificationsService ) {
      // Create 120 users
    const users: UserData[] = [];
    var userdata=[];
    for (let i = 1; i <= 120; i++) { 
    
      userdata.push({"cnt" : i,"name": NAMES[i%15],'progress': Math.round(i/120 *100),'color':COLORS[i%12]});
      
     }

    // Assign the data to the data source for the table to render
    this.dataSource = new MatTableDataSource(userdata);
}
 
   ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  ngOnInit(){
  //this._service.success('nat','dndnnd',this.options);
}

displayedColumns = ['id', 'name', 'progress', 'color'];
  dataSource: MatTableDataSource;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

   applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }
 
 addbut(){
   window.alert("addbutton");
 }
 editbut(){
   window.alert("editbutton");
 }


}


/** Builds and returns a new User. */
function createNewUser(id: number): UserData {
  const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

  return {
    id: id.toString(),
    name: name,
    progress: Math.round(Math.random() * 100).toString(),
    color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
  };
}

/** Constants used to fill up our data. */
const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

export interface UserData {
  id: string;
  name: string;
  progress: string;
  color: string;
}




<div class="example-container mat-elevation-z8">

  <mat-table [dataSource]="dataSource" matSort>

    <!-- ID Column -->
    <ng-container matColumnDef="id">
      <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
      <mat-cell *matCellDef="let row" data-label="id"> {{row.cnt}} </mat-cell>
    </ng-container>

    <!-- Progress Column -->
    <ng-container matColumnDef="progress">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Progress </mat-header-cell>
      <mat-cell *matCellDef="let row" data-label="progress"> {{row.progress}}% </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row" data-label="name"> {{row.name}} </mat-cell>
    </ng-container>

    <!-- Color Column -->
    <ng-container matColumnDef="color">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Color </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]="row.color" data-label="color"> {{row.color}} </mat-cell>
    </ng-container>

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

  <mat-paginator [pageSizeOptions]="[ 10, 25, 100]"></mat-paginator>
</div>


body {
  font-family: 'Covered By Your Grace', cursive;
  line-height: 1.25;
  
}

@media screen and (max-width: 960px) {
  .mat-table {
    border: 0;
    vertical-align: middle
  }

  .mat-table caption {
    font-size: 1em;
  }

  .mat-table .mat-row {
    border-bottom: 5px solid #ddd;
    display: block;
  }
  
  .mat-table .mat-cell {
    border-bottom: 1px solid #ddd;
    display: block;
    font-size: 1em;
    text-align: right;
    font-weight: bold;
    height:30px;
    margin-bottom: 4%;
  }
  .mat-table .mat-cell:before {
  
    content: attr(data-label);
    float: left;
    text-transform: uppercase;
    font-weight: normal;
    
    font-size: .85em;
  }
  .mat-table .mat-cell:last-child {
    border-bottom: 0;
  }
    .mat-table .mat-cell:first-child {
    margin-top: 4%;
  }
}




Output

Below is the full embeded code for the respinsove pagination table using angular material you can easily used in your application.
Example

Spread the love
  •  
  •  
  •  
  •  
  •  
  • 2
  •  
  •  

No Responses