javascript 我如何在Angular中将输入字段格式化为货币

kpbwa7wx  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(132)

我正在处理一个Angular 项目,并且有一个包含以下值的Project类型对象:
成本:56896,人力资源成本:27829
我想使用表单修改对象,并将带有ngModel的字段绑定到属性。
但我面临的问题是,在字段中,我想以货币格式显示数字(例如56,896 €),这与浮动变量类型不兼容。
有人能帮我解决这个问题吗?我试过使用内置的Angular 管道和自定义格式化程序和解析器函数,但它们似乎都没有像预期的那样工作。
任何帮助都将不胜感激。

import { Component, OnInit } from '@angular/core';
import { CurrencyPipe } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [CurrencyPipe]
})
export class AppComponent implements OnInit {

  project = {
    cost: 56896,
    costRH: 27829
  }

  constructor(private currencyPipe: CurrencyPipe) { }

  ngOnInit() {
    this.project.cost = this.currencyPipe.transform(this.project.cost, 'EUR', 'symbol', '1.0-0');
    this.project.costRH = this.currencyPipe.transform(this.project.costRH, 'EUR', 'symbol', '1.0-0');
  }

  onBlur(event, projectProperty) {
    this.project[projectProperty] = this.currencyPipe.parse(event.target.value);
  }

}
<form>
  <label for="cost">Cost</label>
  <input [(ngModel)]="project.cost" (blur)="onBlur($event, 'cost')" [ngModelOptions]="{updateOn: 'blur'}" [value]="project.cost | currency:'EUR':'symbol':'1.0-0'">

  <label for="costRH">Cost RH</label>
  <input [(ngModel)]="project.costRH" (blur)="onBlur($event, 'costRH')" [ngModelOptions]="{updateOn: 'blur'}" [value]="project.costRH | currency:'EUR':'symbol':'1.0-0'">
</form>

我所期待的:我希望输入字段被格式化为货币(例如56,896 €),并且当输入失去焦点时,'projet'对象中的相应属性(cost和costRH)将使用解析值更新。
结果是:输入字段中显示的值未格式化为货币,并且对象中的相应属性未按预期更新。

gpfsuwkq

gpfsuwkq1#

可以使用如下指令

@Directive({
  selector: '[format]',
})
export class FormatDirective implements OnInit {
  format = 'N0';
  digitsInfo = '1.0-0';
  @Input() currency = '$';
  @Input() sufix = '';
  @Input() decimalCharacter = null;
  @Input('format') set _(value: string) {
    this.format = value;
    if (this.format == 'N2') this.digitsInfo = '1.2-2';

    const parts = value.split(':');
    if (parts.length > 1) {
      this.format = value[0];
      this.digitsInfo = parts[1];
    }
  }
  @HostListener('blur', ['$event.target']) blur(target: any) {
    target.value = this.parse(target.value);
  }
  @HostListener('focus', ['$event.target']) focus(target: any) {
    target.value = this.control.value;
  }
  ngOnInit() {
    setTimeout(() => {
      this.el.nativeElement.value = this.parse(this.el.nativeElement.value);
    });
  }
  constructor(
    @Inject(LOCALE_ID) private locale: string,
    private el: ElementRef,
    private control: NgControl
  ) {}
  parse(value: any) {
    let newValue = value;

    if (this.format == 'C2')
      newValue = formatCurrency(value, this.locale, this.currency);
    if (this.format == 'N2')
      newValue = formatNumber(value, this.locale, this.digitsInfo);
    if (this.format == 'N0')
      newValue = formatNumber(value, this.locale, this.digitsInfo);
    if (this.format == 'NX')
      newValue = formatNumber(value, this.locale, this.digitsInfo);
    if (this.decimalCharacter)
      return (
        newValue.replace('.', 'x').replace(',', '.').replace('x', ',') +
        this.sufix
      );

    return newValue + this.sufix;
  }

}

工作原理

<input format="N0" [(ngModel)]="value"/>
<input format="N2" [(ngModel)]="value"/>
<input format="C2" [(ngModel)]="value"/>
<input format="N2" decimalCharacter='.' sufix=' €' [(ngModel)]="value"/>

该指令的思想是,当模糊时,更改“native Element”,但不更改ngControl的值,当焦点返回ngControl的值时
stackblitz

6mw9ycah

6mw9ycah2#

我曾经用Numberal js来格式化数字,它太棒了
您需要的格式是'0,0[.]00 €'
check docs

相关问题