I am building an Angular app that uses the following search: Angular Search
I am filtering data from a REST API. I have followed the tutorial and here is what my filter.pipe.ts looks like:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (!items) {
return [];
}
if (!searchText) {
console.log(items)
return items;
}
searchText = searchText.toString();
return items.filter(it => {
console.log(searchText)
return it.toString().toLocaleLowerCase().includes(searchText);
});
}
}
My issue is that when I search for a player, for example, Messi nothing is returned:
Should return Messi, returns nothing
But when I enter the search: object Object, it returns all the players:
Should return nothing, returns everything
The console shows the objects are broken down and not [object Object] so why is the search filtering like this??
I have tried editing the filter to:
<div *ngFor="let player of player_list | paginate: config | filter: { short_name: searchText }">
But that gave me this error:
TS2345: Argument of type '{ short_name: string; }' is not assignable to parameter of type 'string'.
CodePudding user response:
Why is Angular search filtering by object instead of object data?
This is because it.toString() within transform method results in [object Object] string. So when you enter the searchTerm as object, it matches all the items.
You can replace it.toString() with JSON.stringify(it), but do make sure to log the result of JSON.stringify, so that you are aware of the string that it will produce, and see if that is really what you want to search against.
If you plan to filter against a single item property, then you can pass the property to filter:
<div *ngFor="let player of player_list | paginate: config | filter:'short_name':searchText}"> <!-- Passing 'short_name' -->
and modify the transform method:
transform(items: any[], searchAgainst: string, searchText: string): any[] {
// Some logic
return items.filter(it => {
console.log(searchText)
return it[searchAgainst] && it[searchAgainst].includes(searchText);
});
}
You can build upon the above concept and enhance the code as per your requirement.
