Dave Dave -4 years ago 168
TypeScript Question

Ionic 2: Pipe to filter async list by name property

Q) What is wrong with my syntax/code below?

I want to filter my list of items by the name property. I've tried with the code below, but am getting the error:

Cannot read property 'toLowerCase' of undefined

Note: query is defined as an empty string on page load i.e.

var query = "";

My template:

<ion-card *ngFor="#item of (items | clientNameFilter:query)">
<img [src]="getItemImage(item)" (click)="editItem(item)"/>
<ion-card-content (click)="editItem(item)">
<h2 class="card-title">{{item.name}}</h2>

My filter:

import {Pipe, PipeTransform} from 'angular2/core';
import {Client} from '../interfaces/client';

name: 'clientNameFilter',
pure: false
export class ClientNameFilterPipe implements PipeTransform {
transform(query: string, clients: Client[]) {
return clients.filter(client =>
client.name.toLowerCase().indexOf(query) > -1

Answer Source

The parameters aren't in the right order and the second parameter must be an array:

  name: 'clientNameFilter'
export class ClientNameFilterPipe  implements PipeTransform {
  transform(clients: Client[], params: string[]) {
    let query = params[0];
    return clients.filter(client => 
        client.name.toLowerCase().indexOf(query) > -1

The first parameter is the value / list you want the pipe to be applied on and the second one your parameter(s).

See this doc for more details:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download