Tiago Matos
Tiago Matos

Reputation: 1716

Angular2 Pipe filter by name best approach

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?

Upvotes: 2

Views: 2038

Answers (1)

Bhushan Gadekar
Bhushan Gadekar

Reputation: 13805

No need to return null when value is undefined: In your pipe you can do following:

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

@Pipe({
    name: 'search',
    pure: false
})
@Injectable()
export class SearchPipe implements PipeTransform {
    transform(value: any[], name: any, caseInsensitive: boolean): any {
        if (name !== undefined) {
            // filter users, users which match and return true will be kept, false will be filtered out
            return users.filter((user) => {
                if (caseInsensitive) {
                    return (user.name.toLowerCase().indexOf(name.toLowerCase()) !== -1);
                } else {
                    return (user.name.indexOf(name) !== -1);
                }
            });
        }
        return users;
    }
}

as for your problem , when value is undefined, you can surround your *ngFor by a div which has *ngIf on value,so this will be rendered only when userList is not undefined.

<div *ngIf="usersList">
    <div class="list-item" *ngFor="let user of (usersList | search:userSearch:true)">  
        <!-- true is added for case insensitive search -->
        <div><strong>Name:</strong> {{ user.name }}</div>
        <div><strong>Username:</strong> {{ user.username }}</div>
        <div><strong>Email:</strong> {{ user.email }}</div>
    <hr>
    </div>
</div>

Hope this helps.

Upvotes: 1

Related Questions