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:
-
Create a Reactive Form: First, create a reactive form in your Angular component.
-
Add FormControl for the Input Field: Add a
FormControl
to represent the input field in the form. -
Apply Validators: Apply a custom validator to the FormControl to ensure it only accepts numeric values.
For example, we follow:
- In your component HTML file (
app.component.html
), add an input field within a form group:
<form [formGroup]="numberForm">
<input type="text" formControlName="numericInput">
</form>
- 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';
@Component({
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 = this.formBuilder.group({
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.