首页 > 解决方案 > 如何在过滤器管道中检查未找到数据?

问题描述

我编写了一个自定义表和管道,它也成功过滤了我的表。现在,如果没有可用数据,我想收到“未找到数据”消息。

我必须在我的代码中添加什么?

// Pipe
export class FormControlFilterPipe implements PipeTransform {
  transform(items: any[], field: string, value: string): any[] {
    if (!items || (!value || value === null || value.length < 1)) {
      return items;
    }
    return items.filter((item) => {
      const val = JSON.stringify(Object.values(item.value));
      return (val && val.toLowerCase().indexOf(value.toLowerCase()) >= 0);
    });
  }
}
// Template
<table class="custom-table" formArrayName="rows" *ngIf="rows && rows !== null && !isLoading">
          <thead>
          <tr class="optimize-header-row">
            <th *ngFor="let column of displayedColumns; let columnIndex = index;">
              {{ column.name }}
            </th>
          </tr>
          </thead>
          <tbody>
          <tr *ngFor="let rowControl of rows.controls | filterBySearchText: 'value' :searchTerm; let rowIndex = index">
            <td *ngFor="let column of displayedColumns; let columnIndex = index;">
              <ng-container [formGroupName]="rowIndex">
                <span>
                  <label class="change-label">
                    <input class="edit-input" type="text"[formControlName]="column.attribute">
                  </label>
                </span>
              </ng-container>
            </td>
          </tr>
          </tbody>
        </table>

之后我尝试了以下语句,</table> <div *ngIf="rows.controls.length === 0">No Data in Table</div>但不幸的是它不起作用。

标签: angulartypescriptangular-pipe

解决方案


获取管道转换为变量后的值并使用它来检查空长度或零长度。

let rowControl of (rows.controls | filterBySearchText: 'value') as filteredData

完整示例(注意filteredData.length > 0检查)

<table class="custom-table" formArrayName="rows" *ngIf="rows && rows !== null && !isLoading">
  ...
  <tbody>
  <tr *ngFor="let rowControl of (rows.controls | filterBySearchText: 'value' :searchTerm) as filteredData; let rowIndex = index">
    <ng-container *ngIf="filteredData.length > 0; else emptySearch">
      <td *ngFor="let column of displayedColumns; let columnIndex = index;">
        <ng-container [formGroupName]="rowIndex">
          <span>
            <label class="change-label">
              <input class="edit-input" type="text"[formControlName]="column.attribute">
            </label>
          </span>
        </ng-container>
      </td>
    </ng-container>
    <ng-template #emptySearch>
      "No Data Found"
    </ng-template>
  </tr>
  </tbody>
</table>

推荐阅读