Reza Saadati
Reza Saadati

Reputation: 1274

Angular: How to allow only integer in the textbox using Directive

I am trying to create my first directive. What I want is to simply prevent typing on a text field.

This is what I have tried:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: 'input[numbersOnly]'
})
export class NumberDirective {

  constructor(private _el: ElementRef) { }

  @HostListener('input', ['$event']) onInputChange(event) {
    event.stopPropagation();  
  }

}
<input type="text" ngModel numbersOnly>

But the user is still able to type.

I also tried it with event.preventDefault(); but that also didn't work. What am I doing wrong?

Stackblitz

Upvotes: 0

Views: 224

Answers (2)

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

You are missing the important code :)

You forgot to check the valid inputs so you can use regular expression to allow the intergers:

Directive TS Code:

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

@Directive({
  selector: 'input[numbersOnly]'
})
export class NumbersOnlyDirective {

  constructor(private _el: ElementRef) { }

  @HostListener('input', ['$event']) onInputChange(event) {    
    const val = this._el.nativeElement.value;
    this._el.nativeElement.value = val.replace(/[^0-9]*/g, '');
    if (val !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }
}

Forked_Stackblitz

Upvotes: 3

MullisS
MullisS

Reputation: 278

you have to listen to the keyDown event:

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

@Directive({
  selector: '[appNumbersOnly]'
})
export class NumbersOnlyDirective {

  constructor(private _el: ElementRef) { }

@HostListener('keydown', ['$event'])
  onKeyDown(e: KeyboardEvent) {
    if (
      // Allow: Delete, Backspace, Tab, Escape, Enter
      [46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1 || 
      (e.keyCode === 65 && e.ctrlKey === true) || // Allow: Ctrl+A
      (e.keyCode === 67 && e.ctrlKey === true) || // Allow: Ctrl+C
      (e.keyCode === 86 && e.ctrlKey === true) || // Allow: Ctrl+V
      (e.keyCode === 88 && e.ctrlKey === true) || // Allow: Ctrl+X
      (e.keyCode === 65 && e.metaKey === true) || // Cmd+A (Mac)
      (e.keyCode === 67 && e.metaKey === true) || // Cmd+C (Mac)
      (e.keyCode === 86 && e.metaKey === true) || // Cmd+V (Mac)
      (e.keyCode === 88 && e.metaKey === true) || // Cmd+X (Mac)
      (e.keyCode >= 35 && e.keyCode <= 39) // Home, End, Left, Right
    ) {
      return;  // let it happen, don't do anything
    }
    // Ensure that it is a number and stop the keypress
    if (
      (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&
      (e.keyCode < 96 || e.keyCode > 105)
    ) {
      e.preventDefault();
    }
  }

}

Upvotes: 0

Related Questions