In angular 9 how to make an text input field number only?

Viewed 79

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 Answers

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

<input type="number" ...>
Related