首页 文章

如何将格式化值显示为用户类型,但是将原始值发送到Angular 4 formControl以进行验证和formControl值?

提问于
浏览
1

我是Angular2 / 4的新手 .

我有一个formControlName =“Price”的输入字段,我需要输入值以用户输入的正确的货币格式显示 . 当用户输入“100000”时,我需要将其显示为“Rp100,000”,但原始值应该按原样发送到FormControl值 .

我试过这样的事:

import { Directive, ElementRef, HostListener } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[appPriceInput]'
})
export class PriceInputDirective {
  constructor(private el: ElementRef, private control: NgControl) {}

  @HostListener('ngModelChange')
  onValueChange($event) {
    let value = this.el.nativeElement.value;

    if (value.toLowerCase().indexOf('rp') !== -1) {
      value = this.onRemoveCurrencyPipe(this.el.nativeElement.value);
    }

    const formattedValue = new CurrencyPipe('en').transform(value, 'IDR', 'symbol-narrow', '1.0-0');
    this.control.valueAccessor.writeValue(formattedValue);
  }

  @HostListener('blur')
  onBlur($event) {
    const rawValue = this.onRemoveCurrencyPipe(this.el.nativeElement.value);
    this.control.viewToModelUpdate(rawValue);
  }

  onRemoveCurrencyPipe(data) {
    return data
      .substr(2, data.length)
      .split(',')
      .join('');
  }
}

这是表单组和验证 . 价格应该只是一串数字 .

createMedicineForm() {
    this.medicineForm = this.fb.group({
      medicineName: ['', Validators.required],
      quantity: [1, [Validators.required, Validators.pattern('^[0-9]*$'), Validators.min(1)]],
      unit: ['tablet', Validators.required],
      price: [null, [Validators.required, Validators.pattern('^[0-9]*$')]],
      medicineId: ''
    });
  }

但结果仍然是错误的 . 看来这里的问题是 this.control.valueAccessor.writeValue(formattedValue)this.control.viewToModelUpdate() 的错误实现 .

任何人都知道正确的实施?

谢谢 .

1 回答

  • 0

    通过使用如下的简单css可以实现添加正确的货币格式

    .price {
        position: relative;
        display: block;
    }
    
    .price:before {
        content: "Rp";
        font-size: 18px;
        position: absolute;
        top: 0px;
        left: 75px;
    }
    
    .price> input {
        padding-left: 25px;
    }
    

    Html会

    <div class="price">
    Input here: <input type="text" formControlName="Price"/>
    </div>
    

    根据情况改变padding-left,left的值 .

相关问题