使用angular2限制输入字段的长度

vis*_*hnu 4 angular

我已经实现了使用angular2来限制输入字段的指令.它在桌面浏览器中工作正常,但在android mobile中无法正常工作.

零件

import { LimitToDirective } from '../../../directives/limitedvalidation';
@Component({
  templateUrl: 'build/pages/profile/change-basic-details/change-basic-details.html',
  directives: [LimitToDirective]  
})
export class UpdateBasicDetailsPage {
  constructor(){}
}
Run Code Online (Sandbox Code Playgroud)

指示

 import {Directive, Input} from '@angular/core'
    @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)

模板

<ion-input limit-to="12" type="tel" [formControl]="aadhaarno">
Run Code Online (Sandbox Code Playgroud)

ran*_*al9 10

使用maxlength如下:

<ion-input [maxlength]="12" type="tel" [formControl]="aadhaarno">
Run Code Online (Sandbox Code Playgroud)

  • 噢,这仅验证用户输入 — 它不限制用户在输入字段中输入超过 12 个符号。 (2认同)