Csaba
Csaba

Reputation: 2086

Angular 2.0.0 final - Custom Pipe Filter Returns [object Object]

I'm trying to create a filter using a custom pipe. Can anyone help to see why the filter isn't filtering the mock data? It does not throw an error, it returns [object Object]

You can find the full code here: http://run.plnkr.co/plunks/qwsk86hHLbI26w3HVMdV/

Upvotes: 0

Views: 1435

Answers (1)

Michael Heasell
Michael Heasell

Reputation: 71

You're seeing "Filtered by: [Object object]" because the value of listFilter is really an object, not a string.

You bind listFilter here:

<select type="string" [(ngModel)]="listFilter" (ngModelChange)="showSelected()">
    <option *ngFor="let foodType of foodTypes" [ngValue]="foodType">{{foodType.name}}</option>
</select>

When an item is selected, listFilter will be set to the appropriate value of the foodTypes array, which is defined in app.ts:

foodTypes = [
  { id: 1, name: "Fruits" },
  { id: 2, name: "Spices" },
  { id: 3, name: "Vegetables" }
];

So listFilter will be an object with the keys id and name. Use the name property in your template to show the filter name, e.g:

<div *ngIf='listFilter'>
  <h5>Filtered by: {{listFilter.name}} </h5>
</div>

As for why the list itself isn't being filtered, you're not yet doing anything to filter the products list. You'll want to do something like:

<tr *ngFor='let _product of (_products|productFilter:listFilter)'>
  <td>{{ _product.id }}</td>
  <td>{{ _product.prodName }}</td>
</tr>

and then implement the filter itself appropriately:

export class FilterPipe implements PipeTransform {
    transform(value: IProduct[], filterObject: any): IProduct[] {
        // your code here -- return the filtered list
    }
}

(If you defined an interface for the filter object, you could use it here instead of the any type.)

Check out the angular guide on pipes for more info:

https://angular.io/docs/ts/latest/guide/pipes.html

Upvotes: 4

Related Questions