2017-08-29 28 views
0

我有一个实现DecimalPipe变换()方法,像这样一个简单的自定义管角管https://plnkr.co/edit/eEfXoXdM1OakuX1TjR1N?p=preview
显然,这是没有太大的定制管道,因为它实现了DecimalPipe,但是我的最终目标是让这个管道支持更多的模式,而不是'1.2-2'。我做了一些研究,似乎每个人都使用if/else或switch语句等控制结构。我想这会是这样的:使用多种模式

export class MyDecimalFormatPipe implements PipeTransform { 

    constructor(public decimalPipe: DecimalPipe) {}; 

    transform(value: any) { 
     if (somevalue) { 
      let format = '1.2-2' 
      value = this.decimalPipe.transform(value, format); 
     } 
     else if (othervalue) { 
      let format = '1.4-4' 
      value = this.decimalPipe.transform(value, format); 
     } 
     ... 
     return value 
    } 
} 

这似乎是错误的,“笨重”在我们添加更多的格式模式这种方法会得到相当大的。我想管道应该有一些预先设定的格式模式,将根据输入值进行设置。人们可以为此创建一个方法也许,像这样:

setFormatPattern(inputPattern: string): string { 
    let pattern: any; 
    this.myPatternsArray.forEach(element => { 
     if (element.format === inputPattern) { 
      pattern = element.pattern; 
     } 
    }); 
    return pattern; 
} 

我与挣扎的设计,以及这个问题的实现(代码)。必须有一个更简单的方法...

回答

1

您可以将参数传递到您的管道是这样的:

{{ whatever | mypipe: 'option1' }} 

这将被传递到您的pipe.ts为ARGS:

transform(value: any, args?: string) { 
    switch (args) { 
    case 'option1': 
     return handleOption1(value); 
    case 'option2': 
     return handleOption2(value); 
    ... 
    } 
} 
+0

在这种情况下, d只需使用DecimalPipe格式即可:{{whatever | myDecimalPipe:'1.4-4'}}等等。我正在寻找一个解决方案,其中管道本身存储了一些格式模式。 – MadCatm2

+0

如何在使用管道时定义格式? –

+0

怎么样有'私人myPatterns = [{patternA:'1.4-4'},{patternB:'1.2-2},{patternC:'1.9-9}]' – MadCatm2

0

你可以使用额外的参数,通过它将格式传递到管道,也许你想要这样的东西:

export class MyDecimalFormatPipe implements PipeTransform { 

    constructor(public decimalPipe: DecimalPipe) {}; 

    transform(value: any, format: string) { 
     return this.decimalPipe.transform(value, format); 
    } 
} 

// You then use your pipe like ...: 

{{ something | myDecimalPipe: '1.4-4'}}