20

I'm getting an error as follows:

Cannot read property 'filter' of undefined.

Component template:

<input #input placeholder="Search" id="search">
<div class="item" *ngFor="let item of data | searchPipe: input.value">
  {{item}}
</div>

Pipe code:

@Pipe({
  name: 'searchPipe',
  pure: false
})
export class SearchPipe implements PipeTransform {
  transform(data: any[], searchTerm: string): any[] {
    searchTerm = searchTerm.toUpperCase();
    return data.filter(item => {
      return item.toUpperCase().indexOf(searchTerm) !== -1 
    });
  }
}

What causes the error?

0

2 Answers 2

20

Since the incoming data was null and the filter method was expecting data, thus, this caused the error.

Here's a working implementation:

transform(items: any[], filterQuery: any): any[] {
  if (!filterQuery) return items;
  return items.filter(item => item.whateverProperty.toLowerCase().includes(filterQuery.toLowerCase()));
}
0
4

Try this:

export class SearchPipe implements PipeTransform {
  transform(data: any[], searchTerm: string): any[] {
    if(!data) return [];
    searchTerm = searchTerm.toUpperCase();
    return data.filter(item => {
      return item.toUpperCase().indexOf(searchTerm) !== -1 
    });
  }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.