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

Comments

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 
    });
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.