1

Angular2, in my component.ts, I grab a list of Video Objects and store in _videos:Video[]

In my html, I display the videos,

<tr *ngFor="#video of _videos">

Now I want to create a search input field in the html to filter the videos. I am trying to use pipe:

import {Pipe,PipeTransform} from 'angular2/core';

@Pipe({
  name: 'textfilter'
})

export class TextFilterPipe implements PipeTransform {
  transform(items: any[], args: any[]): any {
    if(args[1].toString().length === 0)
      return items;
    return items.filter(item => item[args[0]].indexOf(args[1]) !== -1);
  }
}

in ts,

private _videoTitleFilter: string ='';

in html,

  <tr>
    <th><input id="videoTitleFilter" placeholder="Filter">{{_videoTitleFilter}}</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
  <tr *ngFor="#video of _videos |textfilter:'title':_videoTitleFilter">

It seems the binding is not working. The pipe works for the first time. Is it right to use pipe here? Or I should create a new array _videoList: Video[], listen to the keyup event with throttle to change the _videoList and use it in *ngFor, instead of _videos ?

CountZero
  • 6,171
  • 3
  • 46
  • 59
Hammer
  • 8,538
  • 12
  • 44
  • 75

1 Answers1

4

You could make your pipe not pure:

@Pipe({
  name: 'textfilter',
  pure: false
})
export class TextFilterPipe implements PipeTransform {
  transform(items: any[], args: any[]): any {
    if(args[1].toString().length === 0)
      return items;
    return items.filter(item => item[args[0]].indexOf(args[1]) !== -1);
  }
}

This question could help you:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360