Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'filter' of undefined

Tags:

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?

like image 299
Sajeetharan Avatar asked Feb 02 '17 01:02

Sajeetharan


2 Answers

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()));
}
like image 70
Shandilya Avatar answered Sep 28 '22 02:09

Shandilya


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 
    });
  }
}
like image 23
Shalom Peles Avatar answered Sep 28 '22 01:09

Shalom Peles