如何在Angular中创建管道?

时间:2019-01-29 15:37:22

标签: 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>

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

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

可以为此建议分步教程。

我尝试过

pipe / 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
    ],

mycomponent.ts

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

mytemplate

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

我按照上述方法操作,但出现错误。

compiler.js:2547未捕获的错误:模板解析错误: TypeError:无法读取未定义的属性“ toUpperCase”(“                                   ] * ngFor =“让item.value的obj;索引为i |排序:'obj.curdate'”> {{obj.curdate}}         

2 个答案:

答案 0 :(得分:2)

我想你的意思是烟斗

This tutorial是非常不错的恕我直言,它应该会对您有所帮助。

一些提取物:

创建管道:

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>

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

编辑:您还会看到the official guide,其中包含很多详细信息。

答案 1 :(得分:0)

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

尝试一下

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