A simple directive designed to handle number inputs. This directive will only allow users to input both positive and negative numbers. You can use this with Template/Reactive forms or as a view only field which does not require change in value.
Possible examples that can be achieved by this directive:
- 111
- 111.11
-
- +111
- +111.11
- -111
- -111.11
Demo for this directive can be found in this Stackblitz example.
npm i ngx-number-input
NPM Package: ngx-number-input
- Register the
NgxNumberInputModulein your app/custom module where required.
import { NgxNumberInputModule } from 'ngx-number-input'
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgxNumberInputModule } from 'ngx-number-input';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, NgxNumberInputModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}- Use the directive
ngxNumberInputin your component HTML.<input type="text" ngxNumberInput="7.3" [(ngModel)]="sample" />Notice the value passed in the directive. This signifies the number of digits required before decimal point and after decimal point. For this example, "7.3" signifies 7 digits before decimal point and 3 digits after decimal points. If no decimal point is required specify "0" after the point. e.g:ngxNumberInput="1.0"
Run ng serve for a dev server. Navigate to http://localhost:{PORT}/. The app will automatically reload if you change any of the source files.
This project is based on NgxNumberInput. I want to thank Sanjiv Kumar for writing this article which helped me to write this. Also want to thanks entire Angular team for creating this awesome framework.