使用角度2 /离子2限制字符串的长度

vis*_*hnu 5 typescript ionic-framework ionic2 ionic3 angular

如何使用angular2将电话号码字段限制为10个字符.我尝试使用ng-maxlenth,但它只在浏览器中工作,但不在Android设备中.

我找到了一个使用角度1的代码片段.但是我如何使用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">
Run Code Online (Sandbox Code Playgroud)

yur*_*zui 10

在angular2中,它看起来像:

@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();
  }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记注册指令,NgModule如:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, LimitToDirective ],
  bootstrap: [ App ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

然后使用它像:

<input limit-to="4" type="number" placeholder="enter first 4 digits: 09XX">
Run Code Online (Sandbox Code Playgroud)

这是Plunker!


seb*_*ras 10

您可以使用maxlengthHTML属性和Angular 2中的attr绑定,而不是使用自定义指令,如下所示:[attr.maxlength]="4"

<ion-input type="text" [(ngModel)]="a.myInput" [attr.maxlength]="4"></ion-input>
Run Code Online (Sandbox Code Playgroud)

您还可以将该属性绑定到Component中的属性,以动态设置最大长度.请看看这个plunker.