angular - 如何以角度格式化数字输入
问题描述
我想要这样的东西(不管分隔符是什么)
我的实际代码如下:
<div class="row center-xs" *ngFor="let item of listItem;let i=index">
<div class="col-xs-12 col-md-10">
<mat-form-field>
<input [disabled]="item.lock!=0" type="number" matInput [placeholder]="item.name" [(ngModel)]="item.concept" >
</mat-form-field>
</div>
</div>
我怎样才能做到这一点?
解决方案
我有一个类似的问题。为了解决它,我使用了这篇文章。我创建了一个稍微修改过的版本以满足我的需要。
import { Directive, ElementRef, forwardRef, HostListener, Input, OnDestroy } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { MAT_INPUT_VALUE_ACCESSOR } from '@angular/material';
import { Subscription } from 'rxjs';
import { formatNumber } from '@angular/common';
@Directive({
selector: 'input[localizedNumericInput]',
providers: [
{ provide: MAT_INPUT_VALUE_ACCESSOR, useExisting: LocalizedNumericInputDirective },
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => LocalizedNumericInputDirective),
multi: true
}
]
})
export class LocalizedNumericInputDirective implements ControlValueAccessor, OnDestroy {
locale = 'en';
decimalMarker: string;
constructor(private element: ElementRef<HTMLInputElement>) {
}
private _value: string | null;
get value(): string | null {
return this._value;
}
@Input('value')
set value(value: string | null) {
this._value = value;
this.formatValue(value);
}
@HostListener('input', ['$event.target.value'])
input(value) {
//Find all numerics, decimal marker(, or .) and -
//It will delete thousandSeparator cos it's always opposite to decimal marker
const regExp = new RegExp(`[^\\d${this.decimalMarker}-]`, 'g');
//Separate value on before and after decimal marker
const [integer, decimal] = value.replace(regExp, '').split(this.decimalMarker);
//Send non localized value, with dot as decimalMarker to API
this._value = decimal ? integer.concat('.', decimal) : integer;
// If decimal separator is last character don't update
// because it will delete . || ,
if (this.isLastCharacterDecimalSeparator(value)) {
this._value = value;
}
// here to notify Angular Validators
this._onChange(this._value);
}
@HostListener('blur')
_onBlur() {
/**
* Adding thousand separators
*/
this.formatValue(this._value);
}
@HostListener('focus')
onFocus() {
this.unFormatValue();
}
_onChange(value: any): void {}
/**
* @param value
* apply formatting on value assignment
*/
writeValue(value: any) {
this._value = value;
this.formatValue(this._value);
}
registerOnChange(fn: (value: any) => void) {
this._onChange = fn;
}
registerOnTouched() {}
isLastCharacterDecimalSeparator(value: any) {
return isNaN(value[value.length - 1]);
}
private formatValue(value: string | null) {
if (value === null) {
this.element.nativeElement.value = '';
return;
}
if (this.isLastCharacterDecimalSeparator(value)) {
this.element.nativeElement.value = value;
return;
}
// Conclude the decimal and thousand separators from locale
const [thousandSeparator, decimalMarker] = formatNumber(1000.99, this.locale).replace(/\d/g, '');
this.decimalMarker = decimalMarker;
//Here value should always come with . as decimal marker thus any other behavior is bug
const [integer, decimal] = value.split('.');
//Group every three elements, and add thousandSeparator after them
this.element.nativeElement.value = integer.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
//Add decimals and decimalMarker if any
if (decimal) {
this.element.nativeElement.value = this.element.nativeElement.value.concat(decimalMarker, decimal);
}
}
private unFormatValue() {
const value = this.element.nativeElement.value;
if (this.isLastCharacterDecimalSeparator(value)) {
return;
}
const regExp = new RegExp(`[^\\d${this.decimalMarker}-]`, 'g');
const [integer, decimal] = value.replace(regExp, '').split(this.decimalMarker);
this._value = integer.concat('.', decimal);
if (value) {
this.element.nativeElement.value = this._value;
} else {
this.element.nativeElement.value = '';
}
}
}
推荐阅读
- java - java - 如何在使用java的selenium中将鼠标悬停在按钮上时变为可见的按钮内选择隐藏的下拉列表
- angular - App初始化时执行多个HTTP请求的最佳方法是什么
- javascript - 转换这种 JSON 结构的最优雅的方法是什么?
- python - 如何计算绝对积分?
- php - 在可能是 405 或 422 的情况下会显示什么 HTTP 响应代码?
- hibernate - 使用 @EmbeddedId 的多对多关系生成为:class 生成的空 id
- pandas - Convert multiple appends values into panda dataframe using python
- c# - 获取“该行已经属于另一个表并且输入数组长于该表中的列数。”
- reactjs - React 应用程序中的内容安全策略没有阻止在线脚本
- html - 无法让 CSS Flex 响应。Divs 离开屏幕