[英]Decimal / Thousand separator (dot and comma) in the calculation results Js and Input field
[英]Thousand comma separator not working for an updating Input value
import { Pipe, PipeTransform } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
@Pipe({name: 'decimalComma'})
export class DecimalCommaPipe implements PipeTransform {
constructor(private currencyPipe: CurrencyPipe){}
addCommas(nStr) {
const thousands = /\B(?=(\d{3})+(?!\d))/g
return nStr.replace(thousands, ',');
}
transform(value: any, ...args: any[]) {
const commaVal = this.currencyPipe.transform(value, '', '', `0.0-0`, '');
const replacedVal = commaVal.toString().replace(/,/g, '');
return this.addCommas(replacedVal);
}
}
并在 component.ts
maxAllowedLength() :void {
this.formGroup.valueChanges.subscribe(data => {
const investLength = data?.investmentAmount?.toString();
const monthlyContriLength = data?.monthlyContributionAmount?.toString();
if(investLength.length) {
let formattedVal = this.cp.transform(data?.investmentAmount)
this.formGroup.patchValue({investmentAmount: formattedVal, emitEvent: false, editModelToViewChange: true})
}
if(monthlyContriLength.length > 6) {
debugger;
let formattedVal = parseInt(monthlyContriLength.substring(0, monthlyContriLength.length-1))
this.formGroup.patchValue({monthlyContributionAmount: formattedVal})
}
})
此代码有效,但仅适用于一次传入的值。 我有一个输入框,一个一个地带来值,并且代码没有更新它。 我尝试添加 addCommas function,因为 currencyPipe 也没有更新传入值的“COMMAS”。
每次检测到值的变化时,都会触发 pipe。
我在 Angular Pipe 中使用它
您可以在输入字段上添加一个 keyup 事件来运行 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.