显然,Angular 2将使用管道,而不是像在Angular1和ng-for一起使用的过滤器来过滤结果,尽管实现似乎仍然很模糊,没有明确的文档。
也就是说,我试图实现的目标可以从以下几个角度来看待
<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>
如何使用管道实现so?
发布于 2015-12-09 04:26:44
基本上,您编写了一个管道,然后可以在*ngFor
指令中使用它。
在您的组件中:
filterargs = {title: 'hello'};
items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];
在模板中,您可以将字符串、数字或对象传递给管道以用于过滤:
<li *ngFor="let item of items | myfilter:filterargs">
在你的管道里:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myfilter',
pure: false
})
export class MyFilterPipe implements PipeTransform {
transform(items: any[], filter: Object): any {
if (!items || !filter) {
return items;
}
// filter items array, items which match and return true will be
// kept, false will be filtered out
return items.filter(item => item.title.indexOf(filter.title) !== -1);
}
}
请记住在app.module.ts
中注册管道;您不再需要在@Component
中注册管道
import { MyFilterPipe } from './shared/pipes/my-filter.pipe';
@NgModule({
imports: [
..
],
declarations: [
MyFilterPipe,
],
providers: [
..
],
bootstrap: [AppComponent]
})
export class AppModule { }
Here's a Plunker演示了如何使用自定义过滤器管道和内置的slice管道来限制结果。
请注意(正如一些评论者指出的那样) there is a reason为什么在Angular中没有内置的过滤器管道。
发布于 2016-06-30 01:00:31
简化方式(由于性能问题,仅在小阵列上使用。在大型数组中,您必须通过代码手动创建过滤器):
请参阅:https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
@Pipe({
name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
transform(items: any[], field : string, value : string): any[] {
if (!items) return [];
if (!value || value.length == 0) return items;
return items.filter(it =>
it[field].toLowerCase().indexOf(value.toLowerCase()) !=-1);
}
}
用法:
<li *ngFor="let it of its | filter : 'name' : 'value or variable'">{{it}}</li>
如果你使用一个变量作为第二个参数,不要使用引号。
发布于 2017-04-20 23:55:22
这是我在没有使用管道的情况下实现的。
component.html
<div *ngFor="let item of filter(itemsList)">
component.ts
@Component({
....
})
export class YourComponent {
filter(itemList: yourItemType[]): yourItemType[] {
let result: yourItemType[] = [];
//your filter logic here
...
...
return result;
}
}
https://stackoverflow.com/questions/34164413
复制相似问题