JavaScript Answers

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

Spread the love

To create an input field that accepts only numbers in an Angular application using TypeScript, you can utilize Angular’s built-in forms and validators.

To do this, we:

  1. Create a Reactive Form: First, create a reactive form in your Angular component.

  2. Add FormControl for the Input Field: Add a FormControl to represent the input field in the form.

  3. Apply Validators: Apply a custom validator to the FormControl to ensure it only accepts numeric values.

For example, we follow:

  1. In your component HTML file (app.component.html), add an input field within a form group:
<form [formGroup]="numberForm">
  <input type="text" formControlName="numericInput">
  1. In your component TypeScript file (app.component.ts), create the form and add validators:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent implements OnInit {
  numberForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.numberForm ={
      numericInput: ['', [Validators.required, this.onlyNumbersValidator]]

  // Custom validator function to allow only numbers
  onlyNumbersValidator(control) {
    if (isNaN(control.value)) {
      return { onlyNumbers: true };
    return null;

In this code, we import necessary Angular modules for forms.

Then we defines a form group (numberForm) in the component class.

In the ngOnInit lifecycle hook, creates the form group and adds a FormControl (numericInput) with the custom validator onlyNumbersValidator.

Next we define a custom validator function onlyNumbersValidator that checks if the input value is not a number.

If it’s not a number, it returns an object indicating validation failure; otherwise, it returns null.

With this setup, your input field will only accept numeric values, and an error will be displayed if a non-numeric value is entered.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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