2017-08-24 65 views
0

我目前格式化从服务器中采用了棱角分明的十进制管,像这样我的组件内的响应:我可以在指令外使用自定义的Angular管道吗?

Component.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-格做这种方式并且不能在模板中使用管道。

我的目标是在自定义管道内移动这个逻辑,并在组件内部的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?

+0

如果您不打算在模板上使用它,为什么还要麻烦编写管道?正如Angular文档中所述,管道是“一种编写显示值转换的方法,您可以在HTML中声明”。最好在服务中编写你的转换代码并按照你的意愿使用它。 – BogdanC

+0

我同意你100%,但这是一个需求...基本上,他们不能在模板中使用它,因为如何AG网格的作品。因此,我们需要一个自定义管道,并将其称为组件中的数据... – MadCatm2

+0

我完全明白这一点。我所说的是,你不需要管道来做到这一点,你只需要一个服务,你的转换逻辑,你要注入你的组件,并在那里使用它来转换你的数据。 – BogdanC

回答

0

虽然首先反对使用管道的逻辑,但我会给你答案。

你可以建立自己的管道是这样的:

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"); 

    } 
} 

现在你有一个使用角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); 
    } 
} 

我已经为你做working plunker here

希望能回答你的问题。

相关问题