Angular-built one-time password input component with complete customization for the web.
Let’s get started learning how to add an OTP component to your angular application.
First, install ng-otp-input package by using the below command
npm install --save ng-otp-input
Now, open app.module.ts file and import NgOtpInputModule.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { NgOtpInputModule } from 'ng-otp-input'; import { RouterModule, Routes } from '@angular/router'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, NgOtpInputModule, FormsModule, RouterModule.forRoot([]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
app.component.html
<ng-otp-input #ngOtpInput (onInputChange)="onOtpChange($event)" *ngIf="showOtpComponent" [config]="config" ></ng-otp-input>
app.component.ts file
import { Component, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'otpinput'; otp: any; showOtpComponent = true; @ViewChild("ngOtpInput", { static: false }) ngOtpInput: any; config = { allowNumbersOnly: true, length: 5, isPasswordInput: false, disableAutoFocus: false, placeholder: "*", inputStyles: { width: "50px", height: "50px", }, }; constructor(private router: Router) {} // OTP Code onOtpChange(otp:any) { this.otp = otp; if (otp.length == 5) { this.validateOtp(); } } setVal(val:any) { this.ngOtpInput.setValue(val); } onConfigChange() { this.showOtpComponent = false; this.otp = null; setTimeout(() => { this.showOtpComponent = true; }, 0); } validateOtp() { console.log('only allow 4 digit'); } }
Here, some conig option for ngotpinput
isPasswordInput : set true for password type input
allowNumbersOnly : we can allow only number in input with this property to set it true.
disableAutoFocus: First input will be auto-focused on component load and to next empty input on setValue execution.Set this flag to true to prevent this behavior.
placeholder: add placeholder by this input placeholder.
inputStyles: it is used to apply style to input element.
length: Number of OTP inputs to be rendered.
letterCase: Set value to Upper or Lower to change the otp to upper case or lower case.
allowKeyCodes: By default numbers alphabets and _ – are allowed. You can define other key codes if needed.
OUTPUT: