I'm brand new to using the Angular 2 framework and I'm attempting 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;
}
}
}
});
}
}
I'm experiencing an issue where the list is not loading initially when the page loads. When I try to search for a string (such as a name or email), the entire list is displayed. I'm unsure exactly what is happening. Can someone assist me?