I have a number input in my HTML and I want it to be an integer, not a floating point number.
So, if I have this:
<input type="number" ng-model="person.age" />
Angular will consider a value of 18.4 to be valid. How can I fix this?
I have a number input in my HTML and I want it to be an integer, not a floating point number.
So, if I have this:
<input type="number" ng-model="person.age" />
Angular will consider a value of 18.4 to be valid. How can I fix this?
I will share part of my code.
In my .ts file I have the following code:
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
...
export class IntegerComponent implements OnInit {
fgInteger: FormGroup;
...
constructor(private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.fgInteger = this.formBuilder.group({
amount: ['', [Validators.required, ..., Validators.pattern('^\\d+$')]]
});
}
}
The pattern into the .ts worked for me:
Also, into my .html file, I have the following code:
<form id="fgInteger" [formGroup]="fgInteger" novalidate #fform="ngForm" (ngSubmit)="onSubmit()">
<mat-form-field appearance="outline">
<mat-label>Amount:</mat-label>
<input name="amount" formControlName="amount" type="number" min="1" step="1" matInput placeholder="Enter the amount.">
</mat-form-field>
</form>
By the way I'm working with Angular Material.
Here is another option that works great for me. It doesn't allow the user to enter non integer values, but intercepts the keyboard entries if invalid and prevents the character from being typed.
<input type="number" min="0" oninput="validity.valid||(value='');" maxlength="3" placeholder="Quantity"/>