简体   繁体   中英

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);
    }
} 

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

You can add a keyup event on the input field to run the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM