Подтвердить что ты не робот

Как показать пустое сообщение в угловом материале таблицы данных, Если данных не найдено

Я использую этот код

 <mat-table #table [dataSource]="dataSource" matSort >
  <ng-container matColumnDef="tache">
    <mat-header-cell *matHeaderCellDef mat-sort-header> tâche </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.tache}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="outil">
    <mat-header-cell *matHeaderCellDef mat-sort-header> outil </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.outil}} </mat-cell>
  </ng-container>  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)">
  </mat-row>
</mat-table>

Итак, как показать пустое сообщение "Нет записи найдено" в таблице данных.

4b9b3361

Ответ 1

Как говорят ошибки, вы можете просто использовать *ngIf. Сравните эти две таблицы здесь:

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 с данными:

displayedColumns = ['Name', 'Age']
dataSource = [{name:'Sara',age:17}, {name: 'John', age: 20}]
dataSourceEmpty = []

Ответ 2

Если вы используете console.log dataSource, вы увидите следующее: пример dataSource

Это не сам источник данных, который является массивом, а dataSource.data. На самом деле dataSource - это класс, который имеет данные свойства, которые содержат то, что вы передаете в MatTableDataSource (https://github.com/angular/material2/blob/master/src/lib/table/table-data-source.ts). Поэтому это то, что вы должны использовать для вашего заявления * ngIf.

<div *ngIf="dataSource.data.length === 0">
No Records Found!
</div>

Надеюсь это поможет!

Ответ 3

Есть два способа показать сообщение об ошибке в HTML

1-й метод с использованием метода If

<div *ngIf="dataSource.length">
  <mat-table #table [dataSource]="dataSource" matSort >
  <ng-container matColumnDef="tache">
    <mat-header-cell *matHeaderCellDef mat-sort-header> tâche </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.tache}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="outil">
    <mat-header-cell *matHeaderCellDef mat-sort-header> outil </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.outil}} </mat-cell>
  </ng-container>  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)">
  </mat-row>
</mat-table>
</div>

<div *ngIf="!dataSource.length">
No Record found
</div>

2-й метод с использованием If else

<div *ngIf="dataSource.length; else noRecord">
  <mat-table #table [dataSource]="dataSource" matSort >
  <ng-container matColumnDef="tache">
    <mat-header-cell *matHeaderCellDef mat-sort-header> tâche </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.tache}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="outil">
    <mat-header-cell *matHeaderCellDef mat-sort-header> outil </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.outil}} </mat-cell>
  </ng-container>  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)">
  </mat-row>
</mat-table>
</div>

<ng-template #noRecord>
 <div>
  No Record found
  </div>
</ng-template>

Ответ 4

<mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide':!(listData!=null && listData.filteredData.length==0)}"></mat-footer-row>

Я смог решить проблему, сделав это. hide это пользовательский CSS

.hide{
    display:none;
} 

Ответ 5

Вы можете поместить его в строку нижнего колонтитула следующим образом:

Определение столбца:

<ng-container matColumnDef="noRecord">
      <td mat-footer-cell *matFooterCellDef>No records found.</td>
</ng-container>

Определение строки нижнего колонтитула:

<ng-template [ngIf]="dataSource.data.length === 0">
    <tr mat-footer-row *matFooterRowDef="['noRecord']"></tr>
</ng-template>

Ответ 6

В более новых версиях Angular не забывайте datasource.data если ваш источник данных имеет тип MatTableDataSource.

Пример:

В файле TypeScript:

// ...
datasource = new MatTableDataSource<object>([]);
// ...

И в файле HTML:

<div *ngIf="datasource.data.length > 0"> 
  <!--Show the table.-->
</div>

<div *ngIf="datasource.data.length === 0">
 <!--Show table is empty message. -->
</div>

Ответ 7

Вы можете просто использовать директиву *ngIf чтобы проверить, не является ли dataSource пустым.

 <mat-table *ngIf="dataSource.length > 0" #table [dataSource]="dataSource" matSort >
  <ng-container matColumnDef="tache">
    <mat-header-cell *matHeaderCellDef mat-sort-header> tâche </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.tache}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="outil">
    <mat-header-cell *matHeaderCellDef mat-sort-header> outil </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.outil}} </mat-cell>
  </ng-container>  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)">
  </mat-row>
</mat-table>

<p *ngIf="dataSource.length === 0">No records found</p>

Ответ 8

В .ts файле

if (this.dataSource.length == 0) {
    this.noDataMessage = true;
} else {
    this.noDataMessage = false;
}

В .html файле

<div *ngIf="noDataMessage">
    <p>{{ 'label.DataNotAvailable' | translate }}</p>
</div>

Ответ 9

Для тех, кто имеет возможность сделать это в Нижнем колонтитуле, я смог сделать это, выполнив следующие шаги в Angular 6/7/8:

1) В вашем [ComponentName].component.html

<table mat-table [dataSource]="dataSourceTable">
    <ng-container matColumnDef="columneName">
            <th mat-header-cell *matHeaderCellDef> Name </th>
            <td mat-cell *matCellDef="let element"> {{element.columnname}} </td>
            <td mat-footer-cell *matFooterCellDef>
                <!-- Display a download button in the footer when data is available-->
                <button mat-raised-button color="primary" 
*ngIf="dataSourceTable.data.length > 0">Download</button>
                <!--Below code is displayed when there is no data-->
                <a mat-button *ngIf="dataSourceTable.data.length === 0">No Data 
Found</a>
            </td>
        </ng-container>
        <!--Below Lines of code generates Header, Row and footer for your table  -->
        <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true;"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;">
        </tr>
        <tr mat-footer-row *matFooterRowDef="displayedColumns; sticky: true"></tr>
    </table>

Ответ 10

Вы можете добавить условие в свой источник данных напрямую, не обращаясь к данным или их длине:

<div *ngIf="!yourDataSource" class="alert alert-primary" role="alert">No data </div>

Ответ 11

Если кто-то использует filter с dataSource, вам следует следить за dataSource.filteredData.length.

т.е.

if (this.dataSource.filteredData.length < 1) {
  this.presentDialog();
}

или

<div class="container" *ngIf="dataSource.filteredData.length < 1">
    // Your message here...
</div>