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

並在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM