How to show empty message in data table angular material, If no data found
Solution 1:
With Angular Material 10 or above If you want to show a message when not data matches the filter, you can use the *matNoDataRow directive.
<tr class="mat-row" *matNoDataRow>
<td class="mat-cell" [attr.colspan]="displayedColumns.length">
No data matching the filter.
</td>
</tr>
Solution 2:
It's like bugs is saying, you can just use *ngIf
. Compare these two tables here:
https://stackblitz.com/edit/angular-w9ckf8
<mat-toolbar color="primary">My empty table</mat-toolbar>
<mat-table #table [dataSource]="dataSourceEmpty" matSort *ngIf="dataSourceEmpty.length > 0">
<ng-container matColumnDef="Name">
<mat-header-cell *matHeaderCellDef mat-sort-header>Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="Age">
<mat-header-cell *matHeaderCellDef mat-sort-header>Age </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.age}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" (click)="row.toggle(row)">
</mat-row>
</mat-table>
<div *ngIf="dataSourceEmpty.length === 0">No records found</div>
<hr>
<mat-toolbar color="primary">My full table</mat-toolbar>
<mat-table #table [dataSource]="dataSource" matSort *ngIf="dataSource.length > 0">
<ng-container matColumnDef="Name">
<mat-header-cell *matHeaderCellDef mat-sort-header>Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="Age">
<mat-header-cell *matHeaderCellDef mat-sort-header>Age </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.age}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" (click)="row.toggle(row)">
</mat-row>
</mat-table>
<div *ngIf="dataSource.length === 0">No data</div>
TS with data:
displayedColumns = ['Name', 'Age']
dataSource = [{name:'Sara',age:17}, {name: 'John', age: 20}]
dataSourceEmpty = []
Solution 3:
You can put it in the footer row this way:
Column definition:
<ng-container matColumnDef="noRecord">
<td mat-footer-cell *matFooterCellDef>No records found.</td>
</ng-container>
Footer row definition:
<ng-template [ngIf]="dataSource.data.length === 0">
<tr mat-footer-row *matFooterRowDef="['noRecord']"></tr>
</ng-template>