2

I have a text input field where I want to apply a custom directive so that user is allowed to only enter numbers. I have created this directive but it seems event.stopPropagation() is not working. Any suggestion?

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

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

  constructor(private _el: ElementRef) {
  }

  @HostListener('input', ['$event']) onInputChange(event) {
    const initalValue = this._el.nativeElement.value;

    this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
    if ( initalValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }
}
  • 1
    Does this answer your question? [Angular2 - Input Field To Accept Only Numbers](https://stackoverflow.com/questions/41465542/angular2-input-field-to-accept-only-numbers) – Yong Shun Jun 04 '21 at 07:57

1 Answers1

1

You can do it without directive. Only you have to do is add type="number".

<input type="number" ...>
N.F.
  • 3,844
  • 3
  • 22
  • 53
  • But that is not the best solution. we need to know why stopPropagation is not working. If u have some other directives that allows only alphanumeric chars. So to make them working u need to fix that issue – Sayed Uz Zaman Jun 04 '21 at 08:08