I wanted to add a custom table filter to my angular code. Did web search and found this blog post:
https://www.code-sample.com/2018/07/angular-6-search-filter-pipe-table-by.html
It works pretty well and here the pipe code:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'gridFilter'
})
/*
I got this code from here:
https://www.code-sample.com/2018/07/angular-6-search-filter-pipe-table-by.html
*/
export class GridFilterPipe implements PipeTransform {
transform(items: any, filter: any, defaultFilter: boolean): any {
if (!filter){
return items;
}
if (!Array.isArray(items)){
return items;
}
if (filter && Array.isArray(items)) {
let filterKeys = Object.keys(filter);
if (defaultFilter) {
return items.filter(item =>
filterKeys.reduce((x, keyName) =>
(x && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] == "", true));
}
else {
return items.filter(item => {
return filterKeys.some((keyName) => {
return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] == "";
});
});
}
}
}
}
It works pretty well for most of my needs except this one table that is this html:
<div class="col-md-4" *ngIf="element == 'location'">
<div class="spacer"></div>
<div class="panel panel--vibblue panel--raised">{{ element | titlecase }}</div>
<div class="responsive-table panel--raised">
<table class="table table--bordered table--hover approvals-table" id="location-table">
<thead>
<tr>
<th class="sortable">{{ element | titlecase }} Name <span class="sort-indicator icon-chevron-down"></span></th>
<th class="sortable">Site <span class="sort-indicator icon-chevron-down"></span></th>
<th>Action</th>
</tr>
</thead>
<tbody>
<ng-container *ngFor="let el of elements | gridFilter: {name: searchText, site:searchText}">
<tr>
<td>{{el.name}}</td>
<td>{{ getSiteName(el.site) }}</td>
<td>
<a><span class="icon-trash" (click)="deleteElement(el.id, el.name)"></span></a>
</td><td>
<a><span class="icon-pencil" (click)="editElement(el)"></span></a>
</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
</div>
The issue with the above table is this. To display the site name of a location I use this html ...
<td>{{ getSiteName(el.site) }}</td>
... which calls a method getSiteName
which takes the id
of a site and returns the site's name. I do not know how to set my gridFilter
. So if I try to search for a site name my gridFilter doesn't find the site.
Here is my stackblitz for this: https://stackblitz.com/edit/angular-damcul
** UPDATE **
I have updated my stackblitz to actually illustrate the problem I am having. Here is a screen shot of the stackblitz app:
I can search for locations and here is the screen shot of me searching for 'loc_2':
But I can not search for sites. Here the screen shot of me searching for any 'site'.