使用角度2 /离子2限制字符串的长度 [英] Limit the length of a string using angular 2/ionic 2

查看:86
本文介绍了使用角度2 /离子2限制字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用angular2将电话号码字段限制为10个字符。
i尝试使用 ng-maxlenth ,但它仅在浏览器中有效,但在Android设备中无效。

How do i restrict the phone number field to 10 characters using angular2. i tried using ng-maxlenth but it is working only in browser but not in the android devices.

我找到了一个代码段使用angular 1.但我如何使用angular2重写相同的代码?

I found one code snippet using angular 1. But how do i rewrite the the same code using angular2?

app.directive("limitTo", [function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            var limit = parseInt(attrs.limitTo);
            angular.element(elem).on("keypress", function(e) {
                if (this.value.length == limit) e.preventDefault();
            });
        }
    }
}]);

<input limit-to="4" type="number" class="form-control input-lg" ng-model="search.main" placeholder="enter first 4 digits: 09XX">


推荐答案

在angular2中,它将如下所示:

In angular2 it will look like:

@Directive({
  selector: '[limit-to]',
  host: {
    '(keypress)': '_onKeypress($event)',
  }
})
export class LimitToDirective {
  @Input('limit-to') limitTo; 
  _onKeypress(e) {
     const limit = +this.limitTo;
     if (e.target.value.length === limit) e.preventDefault();
  }
}

不要忘记在<$ c中注册指令$ c> NgModule 某事:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, LimitToDirective ],
  bootstrap: [ App ]
})
export class AppModule {}

然后使用它:

<input limit-to="4" type="number" placeholder="enter first 4 digits: 09XX">

这是 Plunker

Here is the Plunker!

这篇关于使用角度2 /离子2限制字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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