Search code examples
angularfilterpipeangular-pipe

Angular2: FilterPipe : Cannot read property 'filter' of undefined


I've been trying to build a filter Pipe for my project, which filters through an array of strings. It is working, but still I'm getting an error. I wonder why that is? I would also like to ask if there is a way to make the filter more universal so I can use it for other strings.

Here is the pipe:

import { Pipe, PipeTransform } from '@angular/core';
import {Afdelingen} from "../models";

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(afdeling:Afdelingen[]) {
    return afdeling.filter(afd => afd.afdelingsNaam == 'pediatrie');
    }
}

My HTML was just for testing, but here it goes:

<div *ngFor="let afd of afdeling | filter">
  {{afd.afdelingsNaam}}

</div>

I've also added an image so you can see, it's working, yet I'm getting an error. Error

EDIT: Universal search pipe:

import { Pipe, PipeTransform } from '@angular/core';
import {Afdelingen} from "../models";

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(afdeling:Afdelingen[], value:string) {
    if (!afdeling)
      return afdeling;
    return afdeling.filter(afd => afd.afdelingsNaam == value);
  }
}

Solution

  • You can add this check in your pipe :

    transform(afdeling:Afdelingen[]) {
        if (!afdeling)
            return afdeling;
        return afdeling.filter(afd => afd.afdelingsNaam == 'pediatrie');
    }
    

    So you get rid of breaking exceptions