尽管我的解决方案运行良好,但我想知道在我的情况下在Angular2中使用PIPE的最佳方法是什么。
让我们开始吧。
我有这个json数组https://jsonplaceholder.typicode.com/users
我的PIPE
transform(value: any, name: any): any
{
if (value == null) {
return null;
}
if (name == null) {
return value;
}
return value.filter(user => {
return user.name.indexOf(name) != -1
});
}
首先,当value为null时,我返回null,因为我是根据此无法从Angular 2中读取null的属性'filter'来从API获取数据的?。
if (value == null) {
return null;
}
其次,我返回null,因为我要先获取原始数据而不进行过滤。
if (name == null) {
return value;
}
最后,我根据用户在输入中输入的内容过滤ngFor内部的结果。
user.name.indexOf(name) != -1
输入以过滤数据
<input type="text" [(ngModel)]="userSearch">
我的ngFor
<div class="list-item" *ngFor="let user of (usersList | filterPipe:userSearch)">
<div><strong>Name:</strong> {{ user.name }}</div>
<div><strong>Username:</strong> {{ user.username }}</div>
<div><strong>Email:</strong> {{ user.email }}</div>
<hr>
</div>
那么,你们怎么看?
当value
is时,无需返回null undefined
:在管道中,您可以执行以下操作:
import { Pipe, PipeTransform, Injectable} from '@angular/core';
@Pipe({
name: 'search',
pure: false
})
@Injectable()
export class SearchPipe implements PipeTransform {
transform(value: any[], name: any, caseInsensitive: boolean): any {
if (name !== undefined) {
// filter users, users which match and return true will be kept, false will be filtered out
return users.filter((user) => {
if (caseInsensitive) {
return (user.name.toLowerCase().indexOf(name.toLowerCase()) !== -1);
} else {
return (user.name.indexOf(name) !== -1);
}
});
}
return users;
}
}
至于你的问题,如果value
是undefined
,你可以围绕你的*ngFor
一个div
具有*ngIf
价值,所以,当这将只呈现userList
不undefined
。
<div *ngIf="usersList">
<div class="list-item" *ngFor="let user of (usersList | search:userSearch:true)">
<!-- true is added for case insensitive search -->
<div><strong>Name:</strong> {{ user.name }}</div>
<div><strong>Username:</strong> {{ user.username }}</div>
<div><strong>Email:</strong> {{ user.email }}</div>
<hr>
</div>
</div>
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句