Ionic 4 离子输入只允许数字,限制字母和特殊字符

Div*_*iya 9 typescript ionic-framework ionic4 angular7

我正在 ionic4 中创建一个应用程序,我有一个功能,用户可以输入唯一的整数 (0-9),所以我想限制任何其他字符,即字母、点等。
我试图限制使用以下指令

 @HostListener('input', ['$event']) onInputChange(event) {
    this.inputElement = this._el.nativeElement.getElementsByTagName('input')[0];
    const initalValue = this.inputElement.value;
    this.inputElement.value = initalValue.replace(/[^0-9]*/g, '');
    if (initalValue !== this.inputElement.value) {
       event.stopPropagation();
    }
}
Run Code Online (Sandbox Code Playgroud)

它正在正确更新 ngModel,但仍然在输入字段中可见无效字符。

我尝试了另一种选择,如下所示

html

<ion-input type="text" placeholder="Enter number"
        [(ngModel)]="userCount" 
        name="userCount" 
        (ionInput)="countChange($event)">
 </ion-input>
 Usercount: {{userCount}}
Run Code Online (Sandbox Code Playgroud)

打字稿

countChange(event) {
    event.target.value = event.target.value.replace(/[^0-9]*/g, '');
}
Run Code Online (Sandbox Code Playgroud)

其在 HTML 中的打印值正确无无效字符,但在输入中显示无效字符。

如果我在 input 中输入 5+,ngModel 中的值显示 5 但输入字段显示 5+

当我输入 5++ 然后再次输入 5 时,输入字段现在显示 55。

如何限制输入只接受整数值 [0-9]

小智 17

您应该使用按键事件 这是示例 TS 文件

  numberOnlyValidation(event: any) {
    const pattern = /[0-9.,]/;
    let inputChar = String.fromCharCode(event.charCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
  }
Run Code Online (Sandbox Code Playgroud)

HTML文件

<ion-input type="text" placeholder="Enter number"
        [(ngModel)]="userCount" 
        name="userCount" 
        (keypress)="numberOnlyValidation($event)"
 </ion-input>
Run Code Online (Sandbox Code Playgroud)

它将解决您的问题。

在 Ionic 5 中使用指令:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[appIntegerInput]'
})
export class IntegerInputDirective {

  constructor() { }

  @HostListener('keypress', ['$event'])
  onInput(event: any) {
    const pattern = /[0-9]/; // without ., for integer only
    let inputChar = String.fromCharCode(event.which ? event.which : event.keyCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
      return false;
    }
    return true;
  }

}
Run Code Online (Sandbox Code Playgroud)

HTML文件

<ion-input appIntegerInput inputmode="numeric" type="number"></ion-input>
Run Code Online (Sandbox Code Playgroud)