Angular 2+ - check if Pipe returns an empty subset of original list
This is my code which modified a bit from @Günter Zöchbauer
<div *ngFor="let filter_list of list | FilterItem" >
<div *ngIf=" filter_list == -1 " class="alert alert-info">No item found</div>
<div *ngIf="filter_list !== -1" *ngFor="let item of filter_list ; let i = index;" >
{{ item }}
</div>
</div>
Pipe code
@Pipe({
name: 'FilterItem'
})
export class FilterItem {
transform(list, args?) {
let result = ...;
if ( result && result.length > 0 ){
return [ result ];
}else{
return [ -1 ];
}
}
}
One more way to achieve this is to check the html element for children or in my case the table for rows.
<table #myTable>
<tr *ngFor="let item of list | somePipe : searchText">
<td>{{ item.name }}</td>
</tr>
</table>
<p *ngIf="!myTable.rows.length">No results</p>
<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>