Display filtered array elements by search term with Pipe
1. Component - HTML
.....
<input [(ngModel)]="searchParam" matInput [type]="'text'"> <div *ngFor="let item of allItems | itemFilter : searchParam">
<your-item-entry [property1]="item.property1"
[property2]="item.property2"
[property3]="item.property3"
[property4]="item.property4">
</your-item-entry>
</div>
2. Component - TS
...
allItems: IYourItem[] = []
// fetch your items here
searchParam = '';
...
3. Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'ItemFilter'
})
export class ItemFilterPipe implements PipeTransform {
transform(allItems: IYourItem[], searchText: string): any[] {
if (!allItems) return [];
if (!searchText) return allItems;
// Returns items containing search value (e.g. "codeinpackets") in either of their fields1-4
searchText = searchText.toLowerCase();
return allItems.filter(i => {
return (i.field1 != null && i.field1.toLowerCase().includes(searchText) ||
(i.field2 != null && i.field2.toLowerCase().includes(searchText)) ||
(i.field3 != null && i.field3.toLowerCase().includes(searchText)) ||
(i.field4 != null && i.field4.toLowerCase().includes(searchText))
);
});
}
}
Δεν υπάρχουν σχόλια:
Δημοσίευση σχολίου
What may be missing, or could get better?