Angular 2+ - check if Pipe returns an empty subset of original list

Valdemar Edvard Sandal Rolfsen picture Valdemar Edvard Sandal Rolfsen · May 6, 2016 · Viewed 19.1k times · Source

I have a list of strings that I want to iterate through, but I want to be able to filter them using a search term. Like this:

<div *ngFor="#item in list | search: searchTerm">{{ item }}</div>

My question is: how can I check if the pipe returns an empty subset of the list?

In other words if none of the strings matches the search term, I want to display a message saying: "No matches".

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · May 6, 2016
<div *ngIf="(list | search: searchTerm).length === 0">
  "No matches"
</div>
<div *ngFor="#item in list | search: searchTerm">{{ item }}</div>

Alternatively you could modify your pipe to return a specific token that indicates that the list is empty

@Pipe({
  name: 'search'
})
export class SearchPipe {

  transform(value, searchTerm) {
    let result = ...
    if(result.length === 0) {
      return [-1];
    }
    return result;
  }
}
<ng-container *ngFor="let item of list | search: searchTerm">
  <div *ngIf="item === -1">"No matches"</div>
  <div *ngIf="item !== -1">{{ item }}</div>
</ng-container>