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);
  }
}
4

2 回答 2

4

您可以在管道中添加此检查:

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

所以你摆脱了打破异常

于 2017-05-16T12:58:16.667 回答
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);
  });
}
}
于 2019-05-22T07:56:29.800 回答