Dave Dave - 22 days ago 9
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>
<p>{{item.address.name}}</p>
<p>{{item.address.addressLine1}}</p>
<p>{{item.address.town}}</p>
<p>{{item.address.postcode}}</p>
</ion-card-content>
</ion-card>


My filter:

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

@Pipe({
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

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

@Pipe({
  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:

Comments