Search code examples
angularangular8angular-uiangular-pipe

how to display custom message if data from pipe filter is empty in Angular8


I have a component

<div *ngIf="(StatementData$ | async) as stmtData; else stillLoading">
  <div *ngFor="let p of plans">
    <h3>{{p.planShortName}}</h3>
    <div *ngFor="let s of stmtData.documents | PlanCodePipe : p.planCode">
      <span *ngIf="!s.isDownloading"><a (click)="fetchDocument(s);" class="click-link">{{s.label}}</a></span>
    </div>
  </div>
</div>

i have a pipe filter PlanCodePipe

export class PlanCodePipe implements PipeTransform {
  transform(items: any[], planCode: string): any {
    // console.log("in pipe for", sectionType);
    if (!items) return [];
    return items.filter(x => x.planCode === planCode);
  }
}

like u see in my component , sometimes this filter results in 0 matches.

<div *ngFor="let s of stmtData.documents | PlanCodePipe : p.planCode">

(it filters the documents based on the current plan code from the outer loop) how to catch that and put "No Statements"? which is a tricky part because of the pipe filter i am using.


Solution

  • I think you should not return the filtered items yet. Add a reference variable and check if the filtered items have a length. Create a flag from there if it is more than 0 then return the filtered item else maybe throw an error or a message. Here's my example based on your code.

    export class PlanCodePipe implements PipeTransform {
      transform(items: any[], planCode: string): any {
        // console.log("in pipe for", sectionType);
        const planCode = items.filter(x => x.planCode === planCode);
        const filteredValues = (planCode.length === 0) ? 'No values found' : planCode;
        return filteredValues;
      }
    }