问题描述
我需要阻止负值的类型,并且不允许输入超过99,999,999.99
的数字。
这是我用于货币输入的代码。
<input mask="separator.2" thousandSeparator="," placeholder="Currency">
任何帮助将不胜感激。
这也是Stackblitz示例。
https://stackblitz.com/edit/ngx-mask-currency-input?file=src/app/app.component.html
更新
我找到了问题第二部分的答案。 现在输入看起来像这样
<input mask="separator.2" thousandSeparator="," separatorLimit="10000000" placeholder="Currency">
现在只需要阻止-
字符的类型
解决方法
Demo您可以通过keypress
事件解决
<input (paste)="onPaste($event)" mask="separator.2" thousandSeparator="," separatorLimit="10000000" [allowNegativeNumbers]="false" placeholder="Currency" class="form-control" (keypress)="isPositive($event)">
在组件中
isPositive(event: any) { return event.key === '-' ? false : true; }
并粘贴
onPaste(event){
event.preventDefault();
}
,
2020年1月9日更新
我创建了用于阻止负(-
)类型的指令。
这是指令示例。
import { Directive,ElementRef,OnInit,OnDestroy } from "@angular/core";
import { fromEvent } from "rxjs/internal/observable/fromEvent";
import { Subscription } from "rxjs";
@Directive({
// tslint:disable-next-line: directive-selector
selector: "[onlyPositive]"
})
export class OnlyPositiveDirective implements OnInit,OnDestroy {
subscriber$: Subscription;
constructor(private element: ElementRef<HTMLInputElement>) {}
ngOnInit() {
const input = this.element.nativeElement;
this.subscriber$ = fromEvent(input,'input').subscribe(
(event: KeyboardEvent) => {
if (input.value.includes('-')) {
input.value = input.value.replace(/-/g,'');
}
}
);
}
ngOnDestroy() {
this.subscriber$.unsubscribe();
}
}
用法示例
<input onlyPositive mask="separator.2" thousandSeparator="," separatorLimit="99999999" [allowNegativeNumbers]="false" placeholder="Currency">
在亚当斯建议之后,我已将按键事件更改为 input 事件
演示: https://stackblitz.com/edit/ngx-mask-currency-input?file=src/app/app.component.html