Home > Enterprise >  How to add an empty state in angular custom search pipe
How to add an empty state in angular custom search pipe

Time:02-04

I have a table component, where I am printing the array data using *ngFor.

  <ng-container *ngFor="let element of array | search: searchInput">
        <tr>
          <td >
            <span
              
              [class.update-plugins-second]="element ['status'] === 'unread'"
              [class.update-plugins]="element ['status'] === 'read'"
            ></span>
            <span > {{ report["title"] }} </span>
          </td>
        </tr>
      </ng-container>

Here, I have written custom search pipe like this

import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
  name: "search",
})
export class SearchPipe implements PipeTransform {
  transform(reports: string[], searchInput: string): any[] {
    if (!searchInput) {
      return reports;
    }
    searchInput = searchInput.toLowerCase();
    return reports.filter((x: any) =>
      x?.title.toLowerCase().includes(searchInput)
    );
  }
}

In this case, search functionality is working fine, but I want to add empty state as

<p> No Records Found </p>

when no records found in search pipe.

Where should I write markup for this after current *ngContainer and how should I do this ?

CodePudding user response:

The JS Array#filter function returns an empty array when none of the elements of the array fulfill the condition. So you wrap the pipe in a outer level using a *ngIf and check against the returning array's length. The numeric value 0 is falsy in Javascript, so the else block will be rendered when the array's length is 0.

Also seeing that the CSS selectors update-plugins-second and update-plugins are mutually exclusive based on the value of the status property, it could rewritten using the ngClass directive.

<ng-container *ngIf="(array | search: searchInput) as searchResults">
  <ng-container *ngIf="searchResults.length; else noResults">
    <tr *ngFor="let element of searchResults">
      <td >
        <span
          
          *ngClass="{
            'unread': 'update-plugins-second',
            'read': 'update-plugins'
          }[element['status']]"
        ></span>
        <span > {{ report["title"] }} </span>
      </td>
    </tr>
  </ng-container>
  <ng-template #noResults>
    <p> No Records Found </p>
  </ng-template>
</ng-container>

CodePudding user response:

just add something like this below or above.

<ng-container *ngIf="(array | search: searchInput).lengt === 0">
  No results
</ng-container>
  •  Tags:  
  • Related