NNR NNR - 3 months ago 22
TypeScript Question

Custom Pipes in Angular 2

I am completely new to angular 2 framework. Trying to create a custom filter.

app.component.ts

import {Component} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';

@Component({
selector: 'my-app',
providers: [UserService,HTTP_PROVIDERS],
pipes: [SearchPipe],
templateUrl : `app/user-template.component.html`,
styles:[`
.mt20 { margin-top: 20px; }
.mt30 { margin-top: 30px; }
`]
})

export class AppComponent {
private users = [];
onClick(searchStr){
console.log("textbox value : ",searchStr.value);
}
constructor(private _userService : UserService){
this._userService.getUsersData().subscribe(
data => this.users = data
);
}
}


HTML

<div class="row">
<div class="col-md-4 col-md-offset-4 mt20">
<div class="input-group">
<input type="text" class="form-control" #searchStr>
<span class="input-group-btn">
<button class="btn btn-default" type="button" (click)="onClick(searchStr)">Search</button>
</span>
</div>
</div>
</div>
<hr>
<!-- Cards -->
<div class="container mt30">
<div class="row">
<div class="col-md-3" *ngFor="#user of users | search : searchStr, #i=index">
<div class="card" style="border: 1px solid black; padding:5px; text-align:center;border-radius:5px;">
<div class="card-block">
<h4 class="card-title">{{user.name}}</h4>
<h6 class="card-title">{{user.email}}</h6>
<p class="card-text">{{user.company.catchPhrase}}</p>
<a href="#" class="btn btn-primary">Learn More</a>
</div>
</div>
<div *ngIf="i == 3 || 6">
<br/>
</div>

</div>
</div>
</div>


Pipe

import {Pipe} from 'angular2/core';

@Pipe ({
name : 'search',
pure: false
})

export class SearchPipe {
transform (value, args: any[]){
return value.filter(
(item) => { if(value.length > 0){
for(var i=0; i< value.length; i++){
if(value[i].name == args[0].value || value[i].email == args[0].value){
console.log("Filtered Object :",value[i]);
return value[i];
}else{
return;
}
}
}
});
}
}


Here I am not getting list initially when page loads. And When I search for a string(name or email), getting total list. Don't exactly what is happening. Help me.

Answer

filter takes a function that is run on each of the array's items. It has to return a boolean.

Your class should actually look like this:

export class SearchPipe {
  transform (value: any[], args: any[]){
    const search = args[0].value;

    return value.filter(
      (item) => {
          if(item.name == search || item.email == search){
            console.log("Filtered Object :", item);
            return true
          }else{
            return false;
          }
      });
  }
}

or in a shorter version:

export class SearchPipe {
  transform (value: any[], args: any[]){
    const search = args[0].value;

    return value.filter(item => 
      (item.name == search || item.email == search)
    );
  }
}

Don't search on empty search strings:

export class SearchPipe {
  transform (value: any[], args: any[]){
    const search = args[0].value;

    if (!search) return value;

    return value.filter(item => 
      (item.name == search || item.email == search)
    );
  }
}