Limit the length of input field using angular2

后端 未结 3 725
[愿得一人]
[愿得一人] 2021-01-14 03:57

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

相关标签:
3条回答
  • 2021-01-14 04:40

    Please refer

    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) {
    debugger
    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);
    }
    }
    
    
    <ion-input limit-to="12" type="tel" [formControl]="aadhaarno">
    

    click

    0 讨论(0)
  • 2021-01-14 04:47

    Use maxlength as belows :

    <ion-input [maxlength]="12" type="tel" [formControl]="aadhaarno">
    
    0 讨论(0)
  • 2021-01-14 04:47

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

    0 讨论(0)
提交回复
热议问题