Angular2: Error while using a text filter pipe to filter an array

995 Views Asked by At

I want to be able to search though the categories array by performing a search on the category name. I tried the following solution, but I'm not sure how to edit the variables in the pipe to fit my need.

With the following code, console logs the following error.

categories.component.html:46:10 caused by: item.indexOf is not a function

Template

<tr *ngFor="let category of categories | textFilter:filterText">
    <td>{{category.name}}</td>
    <td>{{category.slug}}</td>
</tr>

Pipe

@Pipe({ name: 'textFilter' })

export class TextFilterPipe
{
  transform(value: any, term: any) {
    if (!term) return value;
    return value.filter((item: any) => item.indexOf(term) > -1);
  }
}
1

There are 1 best solutions below

1
On BEST ANSWER

Your value parameter in the transform function, is an array of objects (category). A javascript object does not have an indexOf function in its prototype, so this is why you are getting this error.

Assuming what you want to do is to filter these object out if none of their properties contain term, then you should do it like:

transform(value: any, term: any) {
  if (!term) return value;
  return value.filter((item: any) => {
    for (let prop in item) {
      if (typeof item[prop] === "string" && item[prop].indexOf(term) > -1) {
        return true;
      }
    }
    return false;
  });
}