The mat table provides a Material Design-styled data table for displaying rows of data.
Step 1:
Create angular application
ng g c material-table
Step 2:
Add Following Package
ng add @angular/material
Step 3:
Include the MatTableModule in your app. The module.ts file
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { MatTableModule } from '@angular/material/table'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, MatTableModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step 4:
Insert the following code into your app.component.ts file.
import {Component} from '@angular/core'; export interface Element { name: string; position: number; weight: number; } const ELEMENT_DATA: Element[] = [ {position: 1, name: 'Hydrogen', weight: 1.0079}, {position: 2, name: 'Helium', weight: 4.0026}, {position: 3, name: 'Lithium', weight: 6.941}, ]; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { displayedColumns: string[] = ['position', 'name', 'weight']; dataSource = ELEMENT_DATA; }
Step 5 :
Insert the following code into your app.component.html file
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <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> <ng-container matColumnDef="weight"> <th mat-header-cell *matHeaderCellDef> Weight </th> <td mat-cell *matCellDef="let element"> {{element.weight}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>
Step 6:
Run your Application using the following code
ng serve