name
管道必须按属性对对象数组进行排序。
按.pipe.ts排序:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sortBy'
})
export class SortByPipe implements PipeTransform {
private name: string;
transform(array: Array<any>, args: string[]): Array<any> {
array.sort((a: any, b: any) => {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
});
return array;
}
}
app.component.html:
<table>
<tr *ngFor="let elem of _values | sortBy">
<td>{{ elem.name }}</td>
<td>{{ elem.ts }}</td>
<td>{{ elem.value }}</td>
</tr>
</table>
app.module.ts:
//other imports
import { SortByPipe } from './sort-by.pipe';
@NgModule({
declarations: [
SortByPipe
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: []
})
export class AppModule { }
对象数组:
[{
"name": "t10",
"ts": 1476778297100,
"value": "32.339264",
"xid": "DP_049908"
}, {
"name": "t17",
"ts": 1476778341100,
"value": "true",
"xid": "DP_693259"
}, {
"name": "t16",
"ts": 1476778341100,
"value": "true",
"xid": "DP_891890"
}];
它不会正确地对对象进行排序,但也不会引发任何错误。
也许我的文件有问题?
任何帮助表示赞赏!