Search code examples
angulartypescriptinputnumbersdirective

Custom behaviour on input type="number" [Angular]


Using Firefox, the user can input letters to an <input type="number"/>. I prevented this with using a custom directive, which only enables characters [0-9].

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

@Directive({
  selector: '[appOnlyNumber]',
})
export class OnlyNumberDirective {
  readonly acceptedKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

  @HostListener('keydown', ['$event']) down(e: any) {
    if (!this.acceptedKeys.includes(e.key)) {
      e.preventDefault();
    }
  }

  constructor(private er: ElementRef) {}
}

However now our coders need to remember to always include this directive, when creating a number input. I want this process to be foolproof, so it is never forgot.

Is there a way to at least warn the programmer that he forget to add this directive? Like checking the DOM after build, and when it contains an input number, but not the directive, than send a warning in the console?

Or can I override the functionality of the default input HTML element, to have this key prevention (0-9 only) by default?


Solution

  • Use an attribute selector in the directive:

    @Directive({
      selector: 'input[type="number"]',
    })