如何在Angular中创建管道?

How to create pipe in Angular?

在Angular中,如何创建管道并应用排序。

我不知道如何创造。 有人可以给我任何指导吗?

1
2
                 {{ obj.curdate }}
         {{ obj.time }}

我在这个问题上看到了很多答案。

但是我不知道在哪里创建该文件以及如何在我的组件中调用。

可以为此建议分步教程。

我试过了

pipe / orderBy.pipe.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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中

1
2
3
4
5
6
import { ArraySortPipe } from './pipe/orderBy.pipe';

@NgModule({
    declarations: [
        ArraySortPipe
    ],

mycomponent.ts

1
import { ArraySortPipe } from '../../../pipe/orderBy.pipe';

我的模板

1
<th *ngFor="let obj of item.value;  index as i | sort: 'obj.curdate'">{{obj.curdate}}</th>

我遵循上述方法,但出现错误。

editor.js:2547未捕获的错误:模板解析错误:
TypeError:无法读取未定义的属性" toUpperCase"("

] * ngFor ="让item.value的obj;索引为i |排序:'obj.curdate'"> {{obj.curdate}}


我想你是说烟斗。

本教程是非常不错的恕我直言,它将为您提供帮助。

一些摘录:

创建您的管道:

1
2
3
4
import { Pipe } from '@angular/core';

@Pipe({ name: 'filesize' })
export class FileSizePipe {}

在您的NgModules上声明

1
2
3
4
5
6
7
8
9
import { FileSizePipe } from './filesize.pipe';

@NgModule({
  declarations: [
    //...
    FileSizePipe,
  ],
})
export class AppModule {}

实施PipeTransform

1
2
3
4
5
export class FileSizePipe implements PipeTransform {
  transform(size: number): string {
    return (size / (1024 * 1024)).toFixed(2) + 'MB';
  }
}

然后就用

1
2
3
<p>
{{ file.size | filesize }}
</p>

本教程有更多详细信息,如果您也有疑问,我可以为您提供帮助。

编辑:您也可以看到具有很多详细信息的官方指南。


我认为您的代码尝试将管道应用到" i"变量,该变量实际上是数组的索引。

尝试这种方式

1
<th *ngFor="let obj of item.value | sort: 'obj.curdate';  index as i">{{obj.curdate}}</th>