Limit the length of a string using angular 2+/ionic 2+

0
1472

In angular 2+ 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">

10

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>

LEAVE A REPLY

Please enter your comment!
Please enter your name here