Angular2从列表

时间:2017-01-23 18:29:21

标签: angular typescript

我正在使用typescript开发angular2应用程序。 我需要通过输入文本框对应过滤用户。

过滤数据后的表格

Input text box

Result

HTML表格视图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.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.ts

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

}

我尝试使用angular2自定义管道来开发它。 我想知道发展? 开发此功能的最佳方式是什么?

1 个答案:

答案 0 :(得分:3)

您可以为过滤器用户使用角度自定义管道。

尝试在代码中添加此类过滤器。

创建新文件user-filter.ts添加这些代码

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;
    }
}

listFilter属性添加到UserListComponent

 export class UserListComponent implements OnInit {

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

更改HTML视图

<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>