Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the length of input field using angular2

Tags:

angular

I have implemented the directive to restrict the input field using angular2. It is working fine in desktop browser, but not working in android mobile.

component

import { LimitToDirective } from '../../../directives/limitedvalidation';
@Component({
  templateUrl: 'build/pages/profile/change-basic-details/change-basic-details.html',
  directives: [LimitToDirective]  
})
export class UpdateBasicDetailsPage {
  constructor(){}
}

directive

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

template

<ion-input limit-to="12" type="tel" [formControl]="aadhaarno">
like image 851
vishnu Avatar asked Dec 19 '22 12:12

vishnu


2 Answers

Use maxlength as belows :

<ion-input [maxlength]="12" type="tel" [formControl]="aadhaarno">
like image 100
ranakrunal9 Avatar answered Jan 10 '23 08:01

ranakrunal9


you should use max-length html5 attribute and then use form validation for Angular2, no custom directive needed.

like image 26
danday74 Avatar answered Jan 10 '23 06:01

danday74