5

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

我找到了一个使用 angular 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">
4

6 回答 6

11

除了使用自定义指令,您还可以maxlength像这样使用 Angular 2 中的 HTML 属性和 attr 绑定:[attr.maxlength]="4"

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

您还可以将该属性绑定到组件中的属性以动态设置最大长度。

于 2016-09-07T07:44:25.290 回答
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();
  }
}

不要忘记在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

于 2016-09-07T05:38:44.813 回答
8

只需使用切片:

{{expression | slice:begin:end}}

角文档: https ://angular.io/docs/ts/latest/cookbook/ajs-quick-reference.html

于 2017-02-16T20:10:26.543 回答
2

我在三星 android 设备上的 ionic2/angular2 中遇到了类似的问题。我已经编写了自定义指令来处理这个问题。我的博客中也提到过,以及其中提到的使用说明。 http://jagadeeshmanne.blogspot.com/2017/08/ionic-2-angular-maxlength-issue-in.html

import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { Platform } from "ionic-angular";
 
@Directive({
    selector: '[cMaxLength]'
})
export class MaxLengthDirective {
 
  @Input('cMaxLength') cMaxLength:any;
  @Output() ngModelChange:EventEmitter<any> = new EventEmitter();
 
  constructor(public platform: Platform) {
  }
 
  //keypress event doesn't work in ionic android. the keydown event will work but the value doesn't effect until this event has finished. hence using keyup event. 
  @HostListener('keyup',['$event']) onKeyup(event) {
    const element = event.target as HTMLInputElement;
    const limit = this.cMaxLength;
    if (this.platform.is('android')) {
      const value = element.value.substr(0, limit);
      if (value.length <= limit) {
        element.value = value;
      } else {
        element.value = value.substr(0, limit-1);
      }
      this.ngModelChange.emit(element.value);
    }
  }
 
  @HostListener('focus',['$event']) onFocus(event) {
    const element = event.target as HTMLInputElement;
    if (!this.platform.is('android')) {
      element.setAttribute('maxlength', this.cMaxLength)
    }
  }
}

于 2017-08-21T13:52:58.023 回答
1

@yurzui 解决方案不适用于安卓设备。正如@Jagadeesh 所提到的,由于某些原因,keypress 事件不会触发。ngModel 更新绑定数据也存在问题。

我建议使用此解决方案:

import {Directive, Input, Output, EventEmitter} from '@angular/core'

@Directive({
  selector: '[limit-to]',
  host: {
    '(input)': 'onInputChange($event)',
  }
})
export class LimitToDirective {
  @Input('limit-to') limitTo;
  @Output() ngModelChange:EventEmitter<any> = new EventEmitter();
  oldValue: any;

  onInputChange(e){
    const limit = +this.limitTo;
    if(e.target.value.length > limit) {
      e.target.value = this.oldValue;
    }
    this.oldValue = e.target.value;
    this.ngModelChange.emit(e.target.value);
  }
}

在输入事件上,检查当前输入值的长度,如果超过限制,则将其替换为最后存储的 oldValue,然后更新输入的显示文本值。并触发一个新的 ngModelChange 事件来更新绑定的属性。

于 2017-08-30T14:16:17.453 回答
0

基于@yurzui angular 4/5 更完整的解决方案 min , max attributes + bug fix for delete

import {Directive, ElementRef, HostListener, Input, OnInit, Renderer} from '@angular/core';

@Directive({
  selector: '[appMaxDigits]'
})
export class MaxDigitsDirective implements OnInit {
    @Input('appMaxDigits') appMaxDigits;
    constructor(private renderer: Renderer, private el: ElementRef) {}
    @HostListener('keydown', ['$event']) onKeydown(e: any) {
        const limit = +this.appMaxDigits;
        if (e.keyCode > 47 && e.keyCode < 127) {
            if (e.target.value.length === limit) { e.preventDefault(); }
        }
    }
    ngOnInit() {
        this.renderer.setElementAttribute(this.el.nativeElement, 'min', '0');
        this.renderer.setElementAttribute(this.el.nativeElement, 'max', '9'.repeat(this.appMaxDigits));
    }
}
于 2018-07-31T17:53:34.733 回答