我正在尝试创建一个将输入值格式化为货币格式的指令。
我能够做我在焦点和模糊上所做的事情,并且在ngOnInit钩子(以及任何其他钩子)中,输入元素还没有应用任何值。
我如何"观看"输入的值,并在应用初始值时对其进行格式化?
这是我的指示:
import {
Input,
Directive,
HostListener,
ElementRef,
Renderer,
OnInit
} from '@angular/core';
import { NgModel } from '@angular/forms';
import { CurrencyPipe } from '@angular/common';
@Directive({
selector: '[currencyInput]',
providers: [NgModel],
host: {
'(input)': 'onInputChange()'
}
})
export class CurrencyInputDirective implements OnInit {
@Input() ngModel: number;
private elem: HTMLInputElement;
constructor(
private el: ElementRef,
private render: Renderer,
private currencyPipe: CurrencyPipe,
private model: NgModel,
) {
this.elem = el.nativeElement;
}
ngOnInit() {
this.elem.value = this.currencyPipe.transform(parseInt(this.elem.value), 'USD', true);
}
@HostListener('focus', ['$event.target.value'])
onFocus(value: string) {
this.elem.value = value.replace(/\,/g, '');
}
@HostListener('blur', ['$event.target.value'])
onBlur(value: string) {
this.elem.value = this.currencyPipe.transform(parseInt(value), 'USD', true);
}
}
答案 0 :(得分:1)
from gtts import gTTS
import os
tts = gTTS(text="This is the pc speaking", lang='en')
tts.save("pcvoice.mp3")
# to start the file from python
os.system("start pcvoice.mp3")
在你的模板中:
ngAfterContentInit() {
this.model.valueChanges.subscribe(value => {
if(value) {
const parsed = parseInt(value.replace('$', ""));
this.model.valueAccessor.writeValue(new CurrencyPipe().transform(parsed, 'USD', true));
}
})
}
答案 1 :(得分:1)
一种可能性是绑定到getter / setter方法,该方法将字段转换为正确的格式,然后在修改后将其恢复为原始格式,如下所示
打字稿:
AnnualRevenue: number;
get AnnualRevenueFormatted():string{
return this.AnnualRevenue !== undefined ? `$${this.AnnualRevenue.toLocaleString()}`: '$0';
}
// strip out all the currency information and apply to Annual Revenue
set AnnualRevenueFormatted(val: string) {
const revenueVal = val.replace(/[^\d]/g, '');
this.AnnualRevenue = parseInt(revenueVal);
}
并在组件视图中
<input type="text" class="text-input" [(ngModel)]="accountInfo.AnnualRevenueFormatted" />
答案 2 :(得分:0)
根据我的指示,我已经应用了这篇文章中提到的解决方案:
ngAfterContentInit() {
this.model.valueChanges.subscribe(value => {
if (value) {
const parsed = parseInt(value.replace('$', ""));
this.model.valueAccessor.writeValue(new CurrencyPipe().transform(parsed, 'USD', true));
}
})
}
它适用于我。
查看我的帖子:Directive display ng-model input value as currency in angular