首页 > 解决方案 > 如何在 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}}

标签: angular

解决方案


我想你的意思是一个管道

本教程非常好,恕我直言,它应该对您有所帮助。

部分摘录:

创建你的管道:

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>

本教程有更多细节,如果您也有疑问,我可以帮助您。

编辑:你也可以看到官方指南,里面有很多细节。


推荐阅读