2017-08-24 62 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

希望能回答你的問題。

相關問題