3

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

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Rakshith
  • 39
  • 1
  • 1
  • 2

7 Answers7

2

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.

Material Data Source

0

its not for serviceDataSource.length its error because you dont Implementation in controller, write :serviceDataSource=[]

miladdn131
  • 72
  • 5
0

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>
Sunil Singh
  • 11,001
  • 2
  • 27
  • 48
0

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>
Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21
0

You can use below if your data coming from API:

*ngIf="serviceDataSource?.length == 0"
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Sunil Game
  • 29
  • 5
0

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

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
0

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>
SantoshK
  • 1,789
  • 16
  • 24