我已经实现了使用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(){}
}
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();
}
}
<ion-input limit-to="12" type="tel" [formControl]="aadhaarno">
答案 0 :(得分:10)
使用maxlength如下:
<ion-input [maxlength]="12" type="tel" [formControl]="aadhaarno">
答案 1 :(得分:3)
你应该使用max-length html5属性,然后对Angular2使用表单验证,不需要自定义指令。
答案 2 :(得分:0)
您可以使用三种方法对输入进行限制。
1-绑定到变量
<ion-input [minlength]="limit" limit-to="12" type="tel" [formControl]="aadhaarno">
2- HTML属性
<ion-input maxlength="12" type="tel" [formControl]="aadhaarno">
3-将验证器用于反应形式
aadhaarno: ['', [Validators.max(12)]]
答案 3 :(得分:0)
请参阅
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) {
debugger
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);
}
}
<ion-input limit-to="12" type="tel" [formControl]="aadhaarno">