嗨,我正在angular13工作,这里我需要允许用户输入正负十进制值,并且必须限制在.
之后的2位小数。在演示中,它可以将用户限制在小数点后2位,但是当按enter键时,我无法执行save。
HTML:
<form [formGroup]="eoInfoForm" (ngSubmit)="save()">
<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
[ngClass]="{
'is-invalid': eoInfo.amount.dirty && eoInfo.amount.invalid
}"
/>
</div>
</div>
</div>
<button type="submit">Save</button>
</form>
TS指令:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[currencyInput]',
})
export class CurrencyInputDirective {
private el: HTMLInputElement;
constructor(private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
@HostListener('keypress', ['$event'])
onkeypress(e: any) {
let event = e || window.event;
if (event) {
return this.allowPositiveNegativeWithTwoDecimal(event);
}
}
allowPositiveNegativeWithTwoDecimal(event: any): any {
let charCode = event.which ? event.which : event.keyCode;
let val = event.target.value.split('.');
let index = event.target.value.indexOf('.');
let minusSplitVal = event.target.value.split('-');
if (
charCode == 45 &&
event.target.selectionStart == 0 &&
(minusSplitVal.length == 1 ||
event.target.selectionEnd == event.target.value.length)
) {
return;
}
if (
event.target.selectionStart == 0 &&
minusSplitVal.length > 1 &&
event.code != 'Delete'
) {
event.preventDefault();
return false;
}
if (
charCode != 46 &&
!(charCode == 37 && event.code == 'ArrowLeft') &&
!(charCode == 39 && event.code == 'ArrowRight') &&
charCode > 31 &&
(charCode < 48 || charCode > 57) &&
!(charCode == 97 && event.ctrlKey == true) &&
event.code != 'Delete'
) {
event.preventDefault();
return false;
}
if (
(charCode == 37 && event.code == 'ArrowLeft') ||
(charCode == 39 && event.code == 'ArrowRight') ||
(charCode == 97 && event.ctrlKey == true)
) {
return;
}
if (charCode == 46 && val.length > 1 && event.code != 'Delete') {
event.preventDefault();
return false;
}
if (event.target.selectionStart < event.target.selectionEnd) {
return;
}
val[0] = val[0].replace('-', '');
if (
val[0].length >= 10 &&
charCode != 46 &&
(index < 0 || event.target.selectionStart <= index) &&
event.code != 'Delete' &&
event.code != 'Backspace' &&
event.code != 'Tab'
) {
event.preventDefault();
return false;
}
if (
val.length > 1 &&
val[1].length == 2 &&
event.target.selectionStart > index &&
event.code != 'Delete' &&
event.code != 'Backspace' &&
event.code != 'Tab'
) {
event.preventDefault();
return false;
}
}
@HostListener('keyup.enter', ['$event.target.value'])
onEnter(value: any) {
return value;
}
}
演示这是因为最后的if语句在回车时被击中了。
if (
val.length > 1 &&
val[1].length == 2 &&
event.target.selectionStart > index &&
event.code != 'Delete' &&
event.code != 'Backspace' &&
event.code != 'Tab'
) {
event.preventDefault();
return false;
}
把这个加进去:&& event.code != 'Enter'
解决方案