6

I am getting this error Cannot read property 'filter' of null

when I apply filter in angular 2 .here is my code

http://plnkr.co/edit/K46jJsnmHiONuqIsnuzW?p=preview

import {Pipe} from 'angular2/core';

@Pipe({
  name: 'sortByName',
  pure: false,
})
export class SortByNamePipe {

  transform (value, [queryString]) {
    // console.log(value, queryString);
    return value.filter((student)=>new RegExp(queryString).test(student.name))
    // return value;
  }
}
Stepan Suvorov
  • 25,118
  • 26
  • 108
  • 176
user944513
  • 12,247
  • 49
  • 168
  • 318

1 Answers1

14

It's because you have data as input that are loaded asynchronously using an HTTP request.

You need to check this before being able to apply the filter:

export class SortByNamePipe {
  transform (value, [queryString]) {
    if (value==null) {
      return null;
    }

    return value.filter((student)=>new RegExp(queryString).test(student.name))
    // return value;
  }
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • To check if the value is null or not. The data will be received, the `transform` method will be called again with a non null value... – Thierry Templier Feb 11 '16 at 10:45
  • 2
    Using `if(value==null) return null;` is better ;-) – Thierry Templier Feb 11 '16 at 10:49
  • still it is not filtering ...:( type test in input field it is not filter list – user944513 Feb 11 '16 at 10:53
  • did you get any idea why it is not filtering the list when we type in input field – user944513 Feb 11 '16 at 10:57
  • I fixed the problem in my plunkr (plnkr.co/edit/rI9rrZ2qlL88xgJpN66z?p=preview). In fact, you need to use an `ngModel` on your input. This way the filter will be reexecuted when the input is updated. Be careful not to use a property in an object. Because Angular2 won't be able to detect changes. This question should help you to understand what happens: http://stackoverflow.com/questions/34456430/ngfor-doesnt-update-data-with-pipe-in-angular2/ (especially the Mark's answer!) – Thierry Templier Feb 11 '16 at 11:00