2017-01-23 70 views
3

我正在用typescript開發angular2應用程序。 我需要通過對應於輸入文本框來過濾用戶。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

歡迎的話,請檢查如何問問題:http://stackoverflow.com/help/how-to-ask因此給我們展示一些代碼,什麼你已經嘗試過,你失敗的地方,謝謝! :) – Alex

+0

你需要發佈一些你自己的代碼。 –

回答

2

您可以爲過濾器用戶使用角度自定義管道。

嘗試添加此類過濾器您的代碼。

創建新文件作爲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> 
+0

不建議使用管道進行過濾。請參閱https://angular.io/docs/ts/latest/guide/pipes.html#!#no-filter-pipe。 – 2017-06-04 13:29:01