How to add an input field to accept only numbers with Angular and TypeScript?

Spread the love

Sometimes, we want to add an input field to accept only numbers with Angular and TypeScript.

In this article, we’ll look at how to add an input field to accept only numbers with Angular and TypeScript.

How to add an input field to accept only numbers with Angular and TypeScript?

To add an input field to accept only numbers with Angular and TypeScript, we check the key pressed in the keypress event handler.

For instance, we write

<input (keypress)="numberOnly($event)" type="text" />

to add an input with a keypress event handler in the template.

Then we write

export class AppComponent {
  numberOnly(event): boolean {
    const charCode = event.which ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;
  }
}

to add the numberOnly method that returns false if a nmumber key isn’t pressed to stop them from being added to the input value.

Otherwise, we let them be added into the input value by returning true.

Conclusion

To add an input field to accept only numbers with Angular and TypeScript, we check the key pressed in the keypress event handler.

Leave a Reply

Your email address will not be published. Required fields are marked *