2

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);
  }
}
1
  • The first time the filter pipe is called, afdeling is probably undefined. You need to check if there is value in afdeling in your pipe :) Commented May 16, 2017 at 12:54

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this solved it. I was also able to make a more universal pipe !
0
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
   name: 'filterbytag'
 })
export class FilterbytagPipe implements PipeTransform {

transform(items: any[], searchText: string): any[] {
if (!items) return [];
if (!searchText) return items;
searchText = searchText.toLowerCase();
  return items.filter(it => {
  return it.toLowerCase().includes(searchText);
  });
}
}

1 Comment

Please, edit your answer and add some description how/why your code solves the issue. Code-only answers are considered as low quality posts

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.