gundra gundra - 8 months ago 102
TypeScript Question

How to filter items inside “ngFor” loop, based on object property string

I need to filter items inside an

loop, by changing the category in a drop-down list. Therefore, when a particular category is selected from the list, it should only list the items containing that same category.

HTML Template:

<option *ngFor="let model of models">{{model.category}}</option>

<ul class="models">
<li *ngFor="let model of models" (click)="gotoDetail(model)">
<img [src]="model.image"/>

Items Array:

export var MODELS: Model[] = [
{ id: 1,
name: 'Model 1',
image: 'img1',
category: 'Cat1',

{ id: 2,
name: 'Model 2',
image: 'img2',
category: 'Cat3',

{ id: 3,
name: 'Model 3',
image: 'img3',
category: 'Cat1',
{ id: 4,
name: 'Model 4',
image: 'img4',
category: 'Cat4',


Also, the drop-down list contains repeated category names. It is necessary for it to list only unique categories (strings).

I know that creating a custom pipe would be the right way to do this, but I don't know how to write one.


Answer Source

Here is a sample pipe:

import { Pipe, PipeTransform } from '@angular/core';

    name: 'matchesCategory'
export class MathcesCategoryPipe implements PipeTransform {
    transform(items: Array<any>, category: string): Array<any> {
        return items.filter(item => item.category === category);

To use it:

<li *ngFor="let model; of models | matchesCategory:model.category" (click)="gotoDetail(model)">

===== for the plunkr example ====

You need your select changes to reflect in some variable

First define in your class a member:

selectedCategory: string;

then update your template:

<select (change)="selectedCategory = $">
   <option *ngFor="let model of models ">{{model.category}}</option>

last, use the pipe:

  <li *ngFor="let model; of models | matchesCategory:selectedCategory" (click)="gotoDetail(model)">