在Angular 2材质滑块中处理美元 [英] Handling dollars in Angular 2 Material Slider
问题描述
我在Angular 2 Material应用程序中有一个表单,其中包括一个价格字段,该价格字段建模为具有最大值,最小值和步长的滑块:
I have a form in my Angular 2 Material application with, among other things, a price field modeled as a slider with a maximum, minimum, and step:
<md-input type="range"
[min]="minimumPrice"
[max]="maximumPrice"
[step]="priceTick"
class="slider">
价格以美分(即没有分数)为模型,但是前端应以美元显示价格,例如,12345
美分的价格现在,最大50000
美分,最小0
美分和5
美分的步长是这样的:
Prices are modeled in cents (i.e. with no fractions), but the front-end should display prices in dollars, e.g., a price of 12345
cents with a maximum of 50000
cents, a minimum of 0
cents, and a step of 5
cents looks like this now:
12345
0 |---------*---------------| 50000
in steps of 5
,但应以美元的形式显示:
$123.45
$0.00 |---------*---------------| $500.00
in steps of $0.05
表单和滑块在显示美分时起作用,但是如何使滑块表现并正确显示以美元为单位的值?
The form and slider work when displayed cents, but how can I get the slider to behave and display correctly with values in dollars?
后端价格模型是long
,它作为long
值发送到前端(即,没有小数部分),但是我愿意更改发送到前端的内容如果需要,可以简化处理.因此,通常的问题是:md-input
正确显示美元并正确行事的最简单方法是什么?
The back-end price model is a long
which is sent to the front-end as a long
value (i.e., with no fractions) but I'm willing to change what I send to the front-end to simplify handling, if need be. So, the general question is: what's the simplest way to get md-input
to display dollars correctly, and behave correctly?
推荐答案
在不完全熟悉Angular2 Material
的情况下,我会冒险使用
Without being entirely familiar with Angular2 Material
I would venture using the CurrencyPipe
combined with a template variable for the slider if you're eschewing model binding:
<md-input type="range" name="slider"
[min]="minimumPrice"
[max]="maximumPrice"
[step]="priceTick"
#slider
class="slider" [placeholder]="slider.value | customCurrency">
<span md-prefix>{{slider.min | customCurrency}}</span>
<span md-suffix>{{slider.max | customCurrency}}</span>
</md-input>
布局可能不正确,但这就是要点,您可以使用此Plunker进行修改
The layout is probably incorrect but that is the gist of it, and you can muck around with this Plunker http://plnkr.co/edit/Fj3hDJmwRD4SvzlKu6R6?p=preview
这是CurrencyPipe
的非常简单的自定义扩展,用于删除/100并设置格式:
Here's a very simple custom extension of the CurrencyPipe
to remove the /100 and set formatting:
custom-currency.pipe.ts
import {Pipe, PipeTransform} from '@angular/core';
import {CurrencyPipe} from '@angular/common';
@Pipe({
name: "customCurrency"
})
export class CustomCurrencyPipe implements PipeTransform {
constructor(private currencyPipe: CurrencyPipe) {}
transform(value: any): string {
return this.currencyPipe.transform(value / 100, 'USD', true);
}
}
module.ts
import {CustomCurrencyPipe} from "[location]/custom-currency.pipe";
import {CurrencyPipe} from "@angular/common";
@NgModule({<...>, declarations: [<...>, CustomCurrencyPipe], providers: [<...>, CurrencyPipe]})
这篇关于在Angular 2材质滑块中处理美元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!