【问题标题】:Can I use custom Angular pipe outside of directive?我可以在指令之外使用自定义 Angular 管道吗?
【发布时间】:2017-08-24 13:55:21
【问题描述】:

我目前正在使用 Angular 十进制管道格式化来自组件内部的服务器的响应,如下所示:

组件.ts

private formatCells(responseData) {
    for (let i = 0; i < responseData.length; i++) {
        if  (responseData[i].value === 0) {
            responseData[i].value = this.decimalPipe.transform(responseData[i].value '1.2-2');
        } else {
            return responseData;
        }
    }
 }

我这样做是因为我使用的是 ag-grid 并且不能在模板中使用管道。

我的目标是将此逻辑移动到自定义管道内,并在我的组件内的 responseData 上调用该管道。也许我不需要自定义管道,因为我只是使用 decimalPipe,但我希望以后可以修改它。

我创建了一个自定义管道并尝试将格式化功能移至管道,但我不确定如何编写转换函数并在组件内的 responseData 上调用它。

myPipe.ts

import { Pipe , PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common';

@Pipe({
    name: 'customDecimalFormat',
    pure: true
})

export class CustomDecimalFormatPipe extends DecimalTransform { 
    transform(value: any) {
       //...?
       return super.transform(value, "1.2-2"); 
    }
}

如何将功能从我的 Component.ts 移动到 myPipe.ts?

【问题讨论】:

  • 如果您不打算在模板上使用管道,为什么还要编写管道呢?如 Angular 文档所述,管道是“一种编写可以在 HTML 中声明的显示值转换的方法”。最好在服务中编写您的转换代码并根据需要使用它。
  • 我 100% 同意你的观点,但这是一个要求......由于 ag-grid 的工作原理,他们基本上不能在模板中使用它。所以我们需要一个自定义管道,并在组件中的数据上调用它...
  • 我完全理解这一点。我要说的是,您不需要管道来执行此操作,您只需要一个带有转换逻辑的服务,您将注入您的组件并在那里使用它来转换您的数据。
  • 是的,同意,它会是一样的......但他们希望它成为一个管道,原因我不完全理解。我别无选择,我必须创建一个自定义管道并将该格式化逻辑从组件移动到管道中。

标签: javascript angular formatting


【解决方案1】:

虽然一开始就违背了使用管道的逻辑,但我会给你答案。

你可以像这样构建你的管道:

import { Pipe, PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common';

@Pipe({
  name: 'custom'
})
export class CustomPipe implements PipeTransform {

 constructor(public decPipe: DecimalPipe) {
  }

 transform(value: any): any {

    //here you can implement your custom logic later on as you wish     

    return this.decPipe.transform(value, "1.2-2");

  }
}

现在您有了使用 Angular DecimalPipe 转换数字的自定义管道。

您可以像这样在 HTML 中使用它:

<div>Used on template:<span *ngFor="let number of numbers">{{number | custom}}</span></div>

或者您可以按照您所说的在组件代码中使用它:

export class App implements OnInit{
  name:string;
  numbers = [1.125439];
  numberFromComponent: number;
  constructor(private customPipe: CustomPipe) {
    this.name = `Angular! v${VERSION.full}`
  }

  ngOnInit() {
    this.numberFromComponent = this.customPipe.transform(1.125439);
  }
}

我已经为你做了一个工作的 plunker here

希望这能回答你的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2017-10-25
    • 2014-03-30
    • 2010-09-12
    • 2019-09-28
    相关资源
    最近更新 更多