简体   繁体   English

千位逗号分隔符不适用于更新输入值

[英]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并在 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.我尝试添加 addCommas function,因为 currencyPipe 也没有更新传入值的“COMMAS”。

On every change detection to the value the pipe is triggered.每次检测到值的变化时,都会触发 pipe。

I am using this in an Angular Pipe我在 Angular Pipe 中使用它

You can add a keyup event on the input field to run the function.您可以在输入字段上添加一个 keyup 事件来运行 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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