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

戏子无情 提交于 2019-12-05 11:10:21

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!

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.

Felipe Sabino

Just use slice:

{{expression | slice:begin:end}}

Angular DOCS: https://angular.io/docs/ts/latest/cookbook/ajs-quick-reference.html

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)
    }
  }
}

@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.

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));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!