How to create directive in angular 2 -- Limit the length of a string using angular 2/ionic 2
In angular2 it will look like:
In angular2 it will look like:
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();
}
}
Don't forget to register directive in NgModule sth like:
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, LimitToDirective ], //keep this in declaration only
bootstrap: [ App ]
})
export class AppModule {}
And then use it like:
<input limit-to="4" type="number" placeholder="enter first 4 digits: 09XX">
https://plnkr.co/edit/sgMubU0p8Z5BPzAIKsf4?p=preview
Confirm Directive
https://plnkr.co/edit/KMfnzrmSx0ywKp6ztaNN?p=preview
Confirm Directive
https://plnkr.co/edit/KMfnzrmSx0ywKp6ztaNN?p=preview
Comments
Post a Comment