
Live Demo - https://rajeshkumaryadav.com/#/auth

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
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';
@NgModule({
declarations: [AppComponent],
imports: [ BrowserModule,
NgOtpInputModule],
bootstrap: [AppComponent]
})
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>
Extra Bits
When I decided to add this to my own website https://rajeshkumaryadav.com/#/auth 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.
auth.component.html
Code: Select all
<ng-otp-input
#ngOtpInput
(onInputChange)="onOtpChange($event)"
*ngIf="showOtpComponent"
[config]="config"
></ng-otp-input>
auth.component.ts
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) {
this.validateOtp();
}
}
setVal(val) {
this.ngOtpInput.setValue(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
}