Angular2 - 仅接受数字的输入字段 [英] Angular2 - Input Field To Accept Only Numbers

查看:33
本文介绍了Angular2 - 仅接受数字的输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular 2 中,如何屏蔽输入字段(文本框),使其只接受数字而不接受字母字符?

In Angular 2, how can I mask an input field (textbox) such that it accepts only numbers and not alphabetical characters?

我有以下 HTML 输入:

I have the following HTML input:

<input 
  type="text" 
  *ngSwitchDefault 
  class="form-control" 
  (change)="onInputChange()" 
  [(ngModel)]="config.Value" 
  (focus)="handleFocus($event)" 
  (blur)="handleBlur($event)"
/>

上面的输入是一个通用的文本输入,它既可以用作简单的文本字段,也可以用作数字字段,例如显示年份.

The above input is a generic text input which may either be used as a simple text field or as a numeric field, for example, to show the year.

使用 Angular 2,我如何使用相同的输入控件并在该字段上应用某种过滤器/掩码,使其仅接受数字?

Using Angular 2, how can I use the same input control and apply some sort of filter/mask on this field, such that it accepts only numbers?

我可以通过哪些不同的方式实现这一目标?

What are the different ways I can achieve this?

注意:我只需要使用文本框而不是使用输入数字类型来实现这一点.

推荐答案

如果你不想要一个指令

https://stackblitz.com/edit/numeric-only

在 component.html

<input (keypress)="numberOnly($event)" type="text">

在 component.ts

export class AppComponent {

  numberOnly(event): boolean {
    const charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;

  }
}

这篇关于Angular2 - 仅接受数字的输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆