How to show no records found in Mat Table Angular?
Assuming this is your code where you are making the API call and creating the mat table data source.
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
dataSource : any = null;
columnsToDisplay = ['name','username','email', 'website'];
constructor(private service : DataService){}
ngOnInit(){
this.service.getUsers().subscribe((response:any) => {
this.dataSource = new MatTableDataSource(response);
})
}
}
Now based on the dataSource
being null or not you can show the table or no records message in your HTML file.
<div class="container">
<table *ngIf="dataSource" mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<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="username">
<th mat-header-cell *matHeaderCellDef> UserName </th>
<td mat-cell *matCellDef="let element"> {{element.username}} </td>
</ng-container>
<ng-container matColumnDef="email">
<th mat-header-cell *matHeaderCellDef> Email </th>
<td mat-cell *matCellDef="let element"> {{element.email}} </td>
</ng-container>
<ng-container matColumnDef="website">
<th mat-header-cell *matHeaderCellDef> Website </th>
<td mat-cell *matCellDef="let element"> {{element.website}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
<tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>
<div *ngIf="!dataSource">
No records found
</div>
</div>