2

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);
  }
}
3
  • have you tried to debug in google console and check which methods item expose for you? Commented Dec 29, 2016 at 10:57
  • I don't know how to do that.. Commented Dec 29, 2016 at 11:07
  • Add console.log(value); before return value.filter...` Commented Dec 29, 2016 at 11:48

1 Answer 1

2

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;
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's perfect!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.