演示 Hi我使用的是angular13,这里我想用2位小数限制输入字段。这是很好的工作,但这个输入必须允许负值以及,我尝试了多种正则模式,但没有工作。
HTML:
<form [formGroup]="eoInfoForm">
<div class="row">
<div class="col">
<div class="form-group">
<label for="">Amount <span class="text-danger">*</span></label>
<input type="text" class="form-control" placeholder="Amount in dolars"
formControlName="amount" autocomplete="off" currencyInput maxDigits="9" [ngClass]="{ 'is-invalid': eoInfo.amount.dirty && eoInfo.amount.invalid }">
</div>
</div>
</div>
</form>指令:
private regexString(max?: number) {
const maxStr = max ? `{0,${max}}` : `+`;
return `^(\\d${maxStr}(\\.\\d{0,2})?|\\.\\d{0,2})$`
}
private digitRegex: RegExp;
private setRegex(maxDigits?: number) {
this.digitRegex = new RegExp(this.regexString(maxDigits), 'g')
}
@Input()
set maxDigits(maxDigits: number) {
this.setRegex(maxDigits);
}
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private currencyPipe: CurrencyPipe
) {
this.el = this.elementRef.nativeElement;
this.setRegex();
}
private default = '';
ngOnInit() {
this.default = this.el.value;
this.el.value = this.currencyPipe.transform(this.el.value, 'USD');
}
@HostListener("focus", ["$event.target.value"])
onFocus(value) {
// on focus remove currency formatting
this.el.value = value.replace(/[^0-9.]+/g, '');
this.el.select();
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
// on blur, add currency formatting
this.el.value = this.currencyPipe.transform(value, 'USD');
}发布于 2022-05-27 04:26:01
你可以使用ngx面具。
npm install --save ngx-mask访问stackblitz:https://stackblitz.com/edit/ngx-mask-ffmmwb?file=src%2Fapp%2Fapp.component.html
https://stackoverflow.com/questions/72400051
复制相似问题