【问题标题】:How to create pipe in Angular?如何在 Angular 中创建管道?
【发布时间】: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


【解决方案1】:

我想你的意思是管道

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,里面有很多细节。

【讨论】:

  • 你没有在该代码的任何地方调用“toUpperCase()”,所以问题很可能出在其他地方
【解决方案2】:

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

试试这个方法

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2014-12-29
    • 2015-03-29
    相关资源
    最近更新 更多