angular - 如何在 Angular 中创建管道?
问题描述
在 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}}
解决方案
我想你的意思是一个管道。
本教程非常好,恕我直言,它应该对您有所帮助。
部分摘录:
创建你的管道:
import { Pipe } from '@angular/core';
@Pipe({ name: 'filesize' })
export class FileSizePipe {}
在你的 NgModules 上声明它
import { FileSizePipe } from './filesize.pipe';
@NgModule({
declarations: [
//...
FileSizePipe,
],
})
export class AppModule {}
实现 PipeTransform
export class FileSizePipe implements PipeTransform {
transform(size: number): string {
return (size / (1024 * 1024)).toFixed(2) + 'MB';
}
}
然后就用它
<p>{{ file.size | filesize }}</p>
本教程有更多细节,如果您也有疑问,我可以帮助您。
编辑:你也可以看到官方指南,里面有很多细节。
推荐阅读
- android - Android中的文本和检查矩形检测
- sql - 搜索比较并生成新表结果
- python - 如何使用 sql.alchemy.orm.validates 使用来自不同表的信息验证表字段?
- javascript - 如何淡化渲染组件的底部边缘直到重新渲染?
- vba - 如何将两个工作簿另存为并镜像它们包含的连接
- mysql - MYSQL 不启动
- html - 将 `text-overflow: ellipsis` 与带有 `display: -webkit-box` 的长且无空格的字符串一起使用
- openlayers - OpenLayers 5 获取范围坐标
- jquery - Jquery Divide 不更新变量
- android - 如何从简单的 Cloud Firestore 结构中检索数据