Issue
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">
Solution
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!
Answered By - yurzui
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.