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?
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()));
}
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
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With