2

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?

2
  • 1
    You can take a look here - it's basically adding custom TSLint rule that traverses the templates and runs validations on nodes. You should be able to write custom rule for this. Commented Apr 19, 2022 at 10:25
  • @GRD this works!, add it as an answer ! Commented Apr 19, 2022 at 13:34

1 Answer 1

3

Use an attribute selector in the directive:

@Directive({
  selector: 'input[type="number"]',
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.