【发布时间】:2019-06-22 18:55:20
【问题描述】:
在 Angular 中,我如何创建管道并应用排序。
我不知道如何创建。任何人都可以在这方面给我任何指导吗?
<div *ngFor="let item of data | keyvalue">
<div *ngFor='let obj of item.value; index as i'>
{{ obj.curdate }}
{{ obj.time }}
</div>
</div>
我看到了很多关于这个问题的答案。
但我不知道在哪里创建这个文件以及如何调用我的组件。
可以建议一步一步的教程。
我试过了,
管道/orderBy.pipe.ts
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "sort"
})
export class ArraySortPipe implements PipeTransform {
transform(array: any, field: string): any[] {
if (!Array.isArray(array)) {
return;
}
array.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
}
在 app.module.ts 中
import { ArraySortPipe } from './pipe/orderBy.pipe';
@NgModule({
declarations: [
ArraySortPipe
],
我的组件.ts
import { ArraySortPipe } from '../../../pipe/orderBy.pipe';
我的模板
<th *ngFor="let obj of item.value; index as i | sort: 'obj.curdate'">{{obj.curdate}}</th>
我按照上面的方法,但我得到了一个错误。
compiler.js:2547 未捕获错误:模板解析错误: TypeError:无法读取未定义的属性“toUpperCase”(“ ]*ngFor="let obj of item.value; index as i | sort: 'obj.curdate'">{{obj.curdate}}
【问题讨论】:
-
对我来说有点不清楚你想要什么。您还可以向我们展示您尝试过的内容或尝试搜索过的内容吗?
-
好吧,我还没有开始,因为我不知道在哪个文件夹下创建 pip 函数以及如何调用它
-
你指的是pipes吗?
-
angular.io/guide/pipes#custom-pipes 有据可查,先试试吧 ;)
-
@ChrisW。你能检查我更新的问题吗
标签: angular