Reputation: 39
I tried the below stackblitz link to display "No records found" message when there is no table data but the problem comes when I use data source of type MatTableDataSource.
stackblitz link: https://stackblitz.com/edit/angular-w9ckf8
Below is the code snippet am using:
this.serviceDataSource = new MatTableDataSource(this.services);
corresponding html:
<table mat-table [dataSource]="serviceDataSource" matSort *ngIf="serviceDataSource.length > 0">
<ng-container *ngFor="let disCol of serviceColumns" matColumnDef="{{disCol}}">
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{disCol}}</th>
<td mat-cell *matCellDef="let rowValue">{{rowValue[disCol]}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="serviceColumns"></tr>
<tr mat-row *matRowDef="let rowdata; columns: serviceColumns;"></tr>
</table>
<div *ngIf="serviceDataSource.length === 0">No records found</div>
Below is the error am getting:
ERROR TypeError: Cannot read property 'length' of undefined
Upvotes: 3
Views: 17709
Reputation: 1877
This is one of the best concept to display no record found in angular 2+.
<p>
<input type="text" [(ngModel)]="name" />
</p>
<ng-container *ngIf="( items | filter : name) as result">
<p *ngFor="let item of result">
{{item.name}}
</p>
<p *ngIf="result.length === 0">No Result</p>
</ng-container>
Upvotes: 0
Reputation: 31
Use this.serviceDataSource.data.length
instead of this.serviceDataSource.length
to get the length of the dataSource.
Check this
In Material Design Page you can see the MatTableDataSource
is using data object to manipulate the data.
Upvotes: 2
Reputation: 10697
You can try by checking variable itseft before going for length
property like:
<span *ngIf="serviceDataSource">
<div *ngIf="serviceDataSource.length === 0">No records found</div>
</span>
StackBlitz with No record found
message
Upvotes: 0
Reputation: 29
You can use below if your data coming from API:
*ngIf="serviceDataSource?.length == 0"
Upvotes: 0
Reputation: 5927
Put a ?
after the variable name which length
will be used here. i.e: serviceDataSource?.length
<div *ngIf="serviceDataSource?.length === 0">No records found</div>
Upvotes: 0
Reputation: 11243
The issue is with accessing of serviceDataSource
before it was initialized. Better would be to have undefined check or simply modify the code as -
<div *ngIf="serviceDataSource?.length === 0">No records found</div>
or
<div *ngIf="serviceDataSource && serviceDataSource.length === 0">No records found</div>
Upvotes: 0
Reputation: 72
its not for serviceDataSource.length
its error because you dont Implementation in controller,
write :serviceDataSource=[]
Upvotes: 0