Tejas
Tejas

Reputation: 97

How to set maxlength to input type number in Angular 6?

I want to restrict the input type="number" with 10 digits but it doesn't accept as I have set maxlength to input type="text". Is there any another way rather than use regex to set maximum length to type="number"?. Is there any another option available (same as input type="text" maxlength="10"), to set length for number easily?

Upvotes: 3

Views: 7313

Answers (1)

Nguyễn Duy
Nguyễn Duy

Reputation: 1

Add this directive

import { Directive, HostListener, ElementRef, OnInit } from '@angular/core';
import { NgModel } from '@angular/forms';

@Directive({
  selector: 'input[type="number"]'
})
export class MaxLengthDirective implements OnInit {

  constructor(private ngModel: NgModel, private el: ElementRef) {}

  private maxLength: number | undefined;

  ngOnInit() {
    const input = this.el.nativeElement as HTMLInputElement;
    const maxLength = input.maxLength;
    if (maxLength) {
      this.maxLength = maxLength;
    }
  }

  @HostListener('input', ['$event'])
  onInput(event: Event) {
    const input = this.el.nativeElement as HTMLInputElement;
    if (input.type === 'number' && this.maxLength) {
      if (input.value.length > this.maxLength) {
        input.value = input.value.slice(0, this.maxLength);
        this.ngModel.control.setValue(input.value);
      }
    }
  }
}

Upvotes: 0

Related Questions