【问题标题】:Angular2 Filter Data From ListAngular2从列表中过滤数据
【发布时间】:2017-01-23 18:29:20
【问题描述】:

我正在使用 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 自定义管道来开发它。 我想知道发展? 开发此功能的最佳方式是什么?

【问题讨论】:

  • 欢迎来到 SO,请查看如何提问:stackoverflow.com/help/how-to-ask 所以给我们看一些代码,你尝试了什么以及你失败的地方,谢谢! :)
  • 您需要为此发布一些您自己的代码。

标签: angular typescript


【解决方案1】:

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

尝试在您的代码中添加这种过滤器。

创建新文件为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>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 2017-10-04
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多