0

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!

1
  • Looks like args is the undefined value here, maybe you could update your filter to only run if args is defined as prior that there is no need to run the filter at all. Commented Apr 10, 2017 at 14:41

1 Answer 1

1

My guess is that since filterItem is empty initially, this prevents the page to load.

In fact it's undefined.

The problem can be fixed doing the following:

transform(value: any, args?: any): any {
  return !!args ? value.filter(item => item.name.indexOf(args[0]) !== -1) : value;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.