如何使用angular2 / typescript限制输入字段中的特殊字符 [英] How to restrict special characters in the input field using angular2/ typescript

查看:606
本文介绍了如何使用angular2 / typescript限制输入字段中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular2的新手。现在我需要限制输入字段中的特殊字符,如果我给它的数字和字母,它必须采取和特殊字符应该被阻止。

在HTML中:
< md-input-container>
< input type =text(ngModelChange)=omit_special_char($ event)mdInput name =name[(ngModel)] =company.nameplaceholder =Company Name#name = ngModelminlength =3required>
< / md-input-container>

在TS中:
public e:any;

  omit_special_char(val)
{
var k;
document.all? k = this.e.keyCode:k = this.e.which; (k> 64& k< 91)||(k>& k< 123)|| k == 8 || k == 32 || (k> = 48& k< = 57));


解决方案

只是功能需要改变一下。您正在使用ngModelChange绑定不存在的事件。您可以使用 keypress 事件处理程序,如下所示。

HTML

 < md-input-container> 
< input type =text(keypress)=omit_special_char($ event)mdInput name =name[(ngModel)] =company.nameplaceholder =Company Name#name = ngModelminlength =3required>
< / md-input-container>

元件

  omit_special_char(event)
{
var k;
k = event.charCode; // k = event.keyCode; (都可以使用)
return((k> 64& k< 91)||(k>& k< 123)|| k == 8 || k == 32 ||(k> = 48& k< = 57));

event是您已经通过的$ event本身的对象早。试试这个,它一定会和angular2一起工作。


I am new to Angular2. Now i need to restrict the special characters in the input field, if i give numbers and alphabets it must take and special characters should be blocked. Can any one help Please.

I am sharing code here:

In HTML:
<md-input-container>
<input type="text" (ngModelChange)="omit_special_char($event)" mdInput name="name" [(ngModel)]="company.name" placeholder="Company Name" #name="ngModel" minlength="3" required>
</md-input-container>

In TS: public e: any;

omit_special_char(val)
{
   var k;
    document.all ? k = this.e.keyCode : k = this.e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

解决方案

You were doing everything right. Just the function needs to be changed a bit. You were using ngModelChange to bind event which is not there. You can use keypress event handler as shown below.

HTML

   <md-input-container>
    <input type="text" (keypress)="omit_special_char($event)" mdInput name="name" [(ngModel)]="company.name" placeholder="Company Name" #name="ngModel" minlength="3" required>
    </md-input-container>

Component

omit_special_char(event)
{   
   var k;  
   k = event.charCode;  //         k = event.keyCode;  (Both can be used)
   return((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57)); 
}

"event" is the object of "$event" itself which you have passed earlier. Try this one, it will surely work with angular2.

这篇关于如何使用angular2 / typescript限制输入字段中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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