Edw*_*ard 8 javascript angular
我有一段代码.
<table class="table table-bordered table-condensed" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr *ngFor="#participant of participants; #i = index">
<td>{{i+1}}</td>
<td>{{participant.username}}</td>
<td>{{participant.score}}</td>
</tr>
</tbody>
</table>Run Code Online (Sandbox Code Playgroud)
在Angular 1中,我有orderBy过滤器来按我的过滤器对行进行排序.但是我怎样才能以相同的方式在Angular 2中进行orderBy?谢谢.
Thi*_*ier 15
您需要为此实现自定义管道.这对应于创建一个由@Pipe修饰的类.这是一个例子.它的转换方法实际上将处理列表,您可以根据需要对其进行排序:
import { Pipe } from "angular2/core";
@Pipe({
name: "orderby"
})
export class OrderByPipe {
transform(array: Array<string>, args: string): Array<string> {
array.sort((a: any, b: any) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return array;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在表达式中使用此管道,如下所述.例如在ngFor中.不要忘记将管道指定到pipes您使用它的组件的属性中:
@Component({
(...)
template: `
<li *ngFor="list | orderby"> (...) </li>
`,
pipes: [ OrderByPipe ]
})
(...)
Run Code Online (Sandbox Code Playgroud)
Ale*_*uev 14
如果你使用lodash你的管道可以是这样的:
import { Pipe, PipeTransform } from '@angular/core';
import { orderBy } from 'lodash';
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform = orderBy;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用该方法的所有功能:
<li *ngFor="let product of products | orderBy: 'price': 'desc'">
{{product.name}}
</li>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42568 次 |
| 最近记录: |