3
votes

I am developing angular2 application with typescript. I need to filter Users by corresponding to input text box.

Table after filtering data

Input text box

Result

HTML Table view users.html

<tr *ngFor='let user of Users'>
        <td>
            <img [src]='user.imageUrl' [title]='user.userName' [style.width.px]='imageWidth' [style.margin.px]='imageMargin'>
        </td>
        <td>{{ user.userName }}</td>
    </tr>

User List user-list.componet.ts

export class UserListComponent implements OnInit {
    imageWidth: number = 50;
    imageMargin: number = 2;
    users: User[] = [
        {
            "productId": 2,
            "productName": "Njjosgaaj",
        }
    ];

    ngOnInit(): void {
        console.log('In OnInit');
    }
}

User Interface user.ts

export interface User {
    userId: number;
    userName: string;

}

I tried to develop this using angular2 custom pipe. I am wondering about development? What is the best way of development this feature?

1
Welcome to SO, please check how to ask a question: stackoverflow.com/help/how-to-ask So show us some code, what you have tried and where you have failed, thanks! :) - AT82
you need to post some of your own code for this. - user9903

1 Answers

3
votes

You can use angular custom pipe for filter users.

Try to add this kind of filter your code.

Create new file as user-filter.ts add these code

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

import { User } from './user';

@Pipe({
    name: 'productFilter'
})
export class UserFilterPipe implements PipeTransform {

    transform(value: User[], filterBy: string): User[] {
        filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
        return filterBy ? value.filter((user: User) =>
            user.userName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
    }
}

Add listFilter attribute to UserListComponent

 export class UserListComponent implements OnInit {

        listFilter: string = 'cart';
        --------------
    }

Change HTML view

<tr *ngFor='let user of Users | userFilter:listFilter '>
        <td>
            <img [src]='user.imageUrl' [title]='user.userName' [style.width.px]='imageWidth' [style.margin.px]='imageMargin'>
        </td>
        <td>{{ user.userName }}</td>
    </tr>