2

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?

2
  • 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! :) Commented Jan 23, 2017 at 18:30
  • you need to post some of your own code for this. Commented Jan 23, 2017 at 18:30

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Using pipe for filtering is not recommended. See angular.io/docs/ts/latest/guide/pipes.html#!#no-filter-pipe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.