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);
}
}
and in the 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})
}
})
This code works but only for a value that is passed in at once. I have an input box that brings value one by one and the code doesnt update it. I tried adding the addCommas function because the currencyPipe was also not updating the "COMMAS" for the values that were coming in.
On every change detection to the value the pipe is triggered.
I am using this in an Angular Pipe