微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ngx-mask货币输入不允许为负值

如何解决ngx-mask货币输入不允许为负值

我需要阻止负值的类型,并且不允许输入超过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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。