Just wondering what is the best approach for using PIPE in Angular2 in my situation, although my solution has worked well.
Let's start it.
I have this json array https://jsonplaceholder.typicode.com/users
My PIPE
transform(value: any, name: any): any
{
if (value == null) {
return null;
}
if (name == null) {
return value;
}
return value.filter(user => {
return user.name.indexOf(name) != -1
});
}
Firstly, I return null when value is null because I am fetching data from API according to this Cannot read property 'filter' of null in angular 2?.
if (value == null) {
return null;
}
Secondly, I return null because I want the original data first without filtering.
if (name == null) {
return value;
}
Last, I filter the result inside the ngFor according to what the user has typed in the input.
user.name.indexOf(name) != -1
Input to filter data
<input type="text" [(ngModel)]="userSearch">
My ngFor
<div class="list-item" *ngFor="let user of (usersList | filterPipe:userSearch)">
<div><strong>Name:</strong> {{ user.name }}</div>
<div><strong>Username:</strong> {{ user.username }}</div>
<div><strong>Email:</strong> {{ user.email }}</div>
<hr>
</div>
So, what do you guys think?