显然,Angular 2将像在Angular1中一样使用管道而不是过滤器,并结合ng-for来过滤结果,尽管实现看起来仍然很模糊,没有明确的文档。
也就是说,我想要达到的目标可以从以下角度来看待
<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>
如何实现这样使用管道?
显然,Angular 2将像在Angular1中一样使用管道而不是过滤器,并结合ng-for来过滤结果,尽管实现看起来仍然很模糊,没有明确的文档。
也就是说,我想要达到的目标可以从以下角度来看待
<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>
如何实现这样使用管道?
当前回答
基于上面提出的非常优雅的回调管道解决方案,可以通过允许传递额外的过滤器参数来进一步泛化它。然后我们有:
callback.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'callback',
pure: false
})
export class CallbackPipe implements PipeTransform {
transform(items: any[], callback: (item: any, callbackArgs?: any[]) => boolean, callbackArgs?: any[]): any {
if (!items || !callback) {
return items;
}
return items.filter(item => callback(item, callbackArgs));
}
}
组件
filterSomething(something: Something, filterArgs: any[]) {
const firstArg = filterArgs[0];
const secondArg = filterArgs[1];
...
return <some condition based on something, firstArg, secondArg, etc.>;
}
html
<li *ngFor="let s of somethings | callback : filterSomething : [<whatWillBecomeFirstArg>, <whatWillBecomeSecondArg>, ...]">
{{s.aProperty}}
</li>
其他回答
这是我不久前创建的一个例子,并在博客上发表过,其中包括一个工作的扑通。它提供了一个过滤管道,可以过滤任何对象列表。基本上你只需要在ngFor规范中指定属性和值{key:value}。
这与@NateMay的回复没有太大不同,只是我比较详细地解释了它。
在我的例子中,我过滤了一个无序列表的一些文本(filterText),用户输入针对对象的“label”属性在我的数组中使用这种标记:
<ul>
<li *ngFor="let item of _items | filter:{label: filterText}">{{ item.label }}</li>
</ul>
https://long2know.com/2016/11/angular2-filter-pipes/
我知道这是一个老问题,但是,我认为提供另一种解决方案可能会有所帮助。
相当于AngularJS的这个
<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>
在Angular 2+中,你不能在同一个元素上使用*ngFor和*ngIf,所以它会如下所示:
<div *ngFor="let item of itemsList">
<div *ngIf="conditon(item)">
</div>
</div>
如果你不能作为内部容器使用ng-container代替。 ng-container在你想有条件地在你的应用程序中添加一组元素(例如使用*ngIf="foo")但不想用另一个元素包装它们时很有用。
在Angular 6中过滤ngFor的一个简单解决方案如下:
<span *ngFor="item of itemsList" > < div * ngIf = " yourCondition(项)" > 你的代码 < / div > < / span >
span很有用,因为它本身并不代表任何东西。
这是我在没有使用管道的情况下实现的。
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;
}
}
管子是最好的方法。但低于1也可以。
<div *ng-for="#item of itemsList">
<ng-container *ng-if="conditon(item)">
// my code
</ng-container>
</div>