How to add A fully customizable, one-time password input component in your angular app just in 10 minutes?

Get support on Angular & Typescript related technology.
Post Reply
Site Admin
Posts: 44

How to add A fully customizable, one-time password input component in your angular app just in 10 minutes?

Post by admin » Thu May 21, 2020 10:11 pm


Live Demo -


You can use this component in your app and extend it to SMS API, here I will skip API part as it varies from sms provider to provider.

Let's begin to learn how to add otp component in your angular app.

Step 1 - Install dependancy

Code: Select all

npm install --save ng-otp-input
Step 2 - Add NgOtpInputModule to imports app.module.ts something like

Code: Select all

import { BrowserModule } from  '@angular/platform-browser';
import { NgModule } from  '@angular/core';
import { AppComponent } from  './app.component';
import { NgOtpInputModule } from  'ng-otp-input';

    declarations: [AppComponent],
    imports: [ BrowserModule,
    bootstrap: [AppComponent]
Here in your existing app you have to add import { NgOtpInputModule } from 'ng-otp-input'; near all existing imports and then add imports in NgModule as NgOtpInputModule with your existing code.

Step 3 - Open your choice of component's ts html file where you want to add OTP feature and add below code -

Code: Select all

<ng-otp-input  (onInputChange)="onOtpChange($event)"  [config]="{length:5}"></ng-otp-input>
All done, OTP component is added.

Extra Bits
When I decided to add this to my own website then I thought of to write config in ts file and pass it in html as below, I will write some more code below which I am using in my website like if all digits are entered then validation should be done etc. If you are happy with default feature you can skip this extra bits part.


Code: Select all

as my config list is long, I will define it in ts file


Code: Select all

 otp: string;
  showOtpComponent = true;
  @ViewChild("ngOtpInput", { static: false }) ngOtpInput: any;
  config = {
    allowNumbersOnly: true,
    length: 4,
    isPasswordInput: false,
    disableAutoFocus: false,
    placeholder: "*",
    inputStyles: {
      width: "50px",
      height: "50px",

  constructor(private router: Router) {}

  // OTP Code
  onOtpChange(otp) {
    this.otp = otp;
    // When all 4 digits are filled, trigger OTP validation method
    if (otp.length == 4) {

  setVal(val) {

  onConfigChange() {
    this.showOtpComponent = false;
    this.otp = null;
    setTimeout(() => {
      this.showOtpComponent = true;
    }, 0);
  validateOtp() {
   // write your logic here to validate it, you can integrate sms API here if you want 
Please note that in above config, you can make necessary changes as per your requirements.

Post Reply