有没有办法以角度反应形式为输入字段中的数字动态添加逗号?



我想在输入字段中输入数字时,每 3 位数字后添加逗号。 此时使用 (blur(,导致从输入字段中删除焦点后出现逗号。我希望这个过程更顺畅。

看看下面的解决方案

<div>
<h2>Hello {{name}}</h2>
<form [formGroup]="profileForm" class="example-form">
<input decimal-mask placeholder="Amount"  formControlName="amount">
</form>
<div>{{profileForm.value.amount}}</div>
</div>

在组件中.ts

profileForm: FormGroup;
ngOnInit() {
this.profileForm = new FormGroup({
amount: new FormControl("")
});
}
@Directive({
selector: "[decimal-mask]"
})
export class DecimalMask {
constructor(private el: ElementRef, public model: NgControl) {}
@HostListener("input", ["$event"]) onEvent($event) {
console.log("keypress: " + $event.keypress);
var valArray = this.el.nativeElement.value.split(".");
for (var i = 0; i < valArray.length; ++i) {
valArray[i] = valArray[i].replace(/D/g, "");
}
let newVal = "";
if (valArray.length === 0) {
newVal = "";
} else {
let matches = valArray[0].match(/[0-9]{3}/gim);
if (matches !== null && valArray[0].length > 3) {
let commaGroups = Array.from(
Array.from(valArray[0])
.reverse()
.join("")
.match(/[0-9]{3}/gim)
.join()
)
.reverse()
.join("");
let replacement = valArray[0].replace(
commaGroups.replace(/D/g, ""),
""
);
newVal =
(replacement.length > 0 ? replacement + "," : "") + commaGroups;
} else {
newVal = valArray[0];
}
if (valArray.length > 1) {
newVal += "." + valArray[1].substring(0, 2);
}
}
// set the new value
this.model.control.setValue(newVal);
//this.model.valueAccessor.writeValue(newVal);
}
}

工作堆栈闪电战

最新更新