Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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".

like image 449
Valdemar Edvard Sandal Rolfsen Avatar asked May 06 '16 07:05

Valdemar Edvard Sandal Rolfsen


1 Answers

<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> 
like image 158
Günter Zöchbauer Avatar answered Sep 29 '22 11:09

Günter Zöchbauer