可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
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">
回答1:
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();
}
}
Don't forget to register directive in NgModule
sth like:
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, LimitToDirective ],
bootstrap: [ App ]
})
export class AppModule {}
And then use it like:
<input limit-to="4" type="number" placeholder="enter first 4 digits: 09XX">
Here is the Plunker!
回答2:
Instead of using a custom directive, you could just use the maxlength
HTML attribute and the attr binding from Angular 2 like this: [attr.maxlength]="4"
<ion-input type="text" [(ngModel)]="a.myInput" [attr.maxlength]="4"></ion-input>
You can also bind that attribute to a property from your Component to set the max length dynamically. Please take a look at this plunker.
回答3:
Just use slice:
{{expression | slice:begin:end}}
Angular DOCS:
https://angular.io/docs/ts/latest/cookbook/ajs-quick-reference.html
回答4:
I have faced the similar issue in ionic2/angular2 on samsung android devices.
I have written the custom directive to handle this.
Same mentioned in my blog and usage instructions mentioned in that.
http://jagadeeshmanne.blogspot.in/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)
}
}
}
回答5:
@yurzui solution didn't work on android device. the keypress event does not fire for some reasons, as mentioned by @Jagadeesh. Also there are issues updating binded data by ngModel.
I suggest this solution instead:
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);
}
}
on input event, check the length of the current input value, if it exceeded the limit, replace it by the last stored oldValue, then update the displayed text value of the input. and fire a new ngModelChange event to update the binded property.
回答6:
based on @yurzui angular 4/5
more complete solution
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));
}
}