I am trying to filter a table using a pipe. This is the code of my filter.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myFilter'
})
export class MyFilterPipe implements PipeTransform {
transform(value: any, args?: any): any {
return value.filter(item => item.name.indexOf(args[0]) !== -1);
}
}
I imported the filter in my app.module.ts
import { MyFilterPipe } from './common/my-filter.pipe';
@NgModule({
declarations: [
MyFilterPipe
],
This is my code for the view HTML
<md-input-container>
<md-icon>search</md-icon>
<input mdInput placeholder="Favorite food" [(ngModel)]="filterItem">
</md-input-container>
...
<table>
<tr *ngFor="let item of items | myFilter: filterItem">
<td>
<a href="#">
<span >
{{item.name}}
</span>
</a>
</td>
<td>
<div>{{item.value1}}</div>
<div>{{item.value2}}</div>
</td>
<td>
<span >
item.description
</span>
</td>
</tr>
</table>
When I try to view the page, I have this error in the browser: "Cannot read property '0' of undefined." Because of the filter, the page doesn't want to load. My guess is that since filterItem is empty initially, this prevents the page to load. But I don't know how to solve it.
Any help will be greatly appreciated! Thanks!
argsis the undefined value here, maybe you could update your filter to only run ifargsis defined as prior that there is no need to run the filter at all.