0

I'm filtering the items using the pipe to filter

My Input filed is in the search.html file and Itemlist in the List.html file

Change in the model is not triggering the pipe transform. Please help. Below is the code snippet.

Search.html

<input placeholder="keyword..." [(ngModel)]="search"/>

List.html

<div *ngFor="let item of items | searchPipe:'name':search ">
  {{item.name}}
</div>

Search.pipe.ts

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

@Pipe({
  name : 'searchPipe',
})
export class SearchPipe implements PipeTransform {
  public transform(value, key: string, term: string) {
    return value.filter((item) => {
      if (item.hasOwnProperty(key)) {
        if (term) {
          let regExp = new RegExp('\\b' + term, 'gi');
          return regExp.test(item[key]);
        } else {
          return true;
        }
      } else {
        return false;
      }
    });
  }
}
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Sanjaybxl
  • 63
  • 8

1 Answers1

2

Ok, based on our discussion and plunks i think i have an answer. Basically what you were missing is communication between components

Search component:

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'my-search',
  template: `
    <input placeholder="keyword..." [(ngModel)]="search" (keyup)=onChange()/>
    `
})

export class SearchComponent {
  search: String;
  @Output() onSearchChange = new EventEmitter<Object>();

  onChange($event) {
    this.onSearchChange.emit(this.search);
  }
}

then some parent component (with list)

import { Component } from '@angular/core';
import { SearchComponent }  from './search.component';

@Component({
  selector: 'my-app',
  template: `
   <h1>Search pipe test</h1>
    Search:  <my-search (onSearchChange)="search = $event"></my-search>
    <br/>    
    <br/>
      <div *ngFor="let item of items | searchPipe:'name':search ">
        {{item.name}}
      </div>
    `
})
export class AppComponent {
  search: String;
  items: Array<any> = [
    { id: 1, name: 'aaaaa' },
    { id: 2, name: 'bbbbb' },
    { id: 3, name: 'ccccc' },
    { id: 4, name: 'aabb' },
    { id: 5, name: 'bbcc' },
  ]
}

and finally working plunk: http://plnkr.co/edit/TzNQfDQ8K7d81ST9qKj5?p=preview

chrystian
  • 831
  • 7
  • 15