Install ngx-otp-input
Install the ngx-otp-input
library via npm:
npm i ngx-otp-input
Import NgxOtpInputModule
Add the NgxOtpInputModule to your application. Open app.module.ts
and update it as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
import { NgModule } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from "./app.component"; import { NgxOtpInputModule } from "ngx-otp-input"; @NgModule({ imports: [BrowserModule, FormsModule, ReactiveFormsModule, NgxOtpInputModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} |
4. Add a Basic OTP Input Example
Now let’s add a simple example of creating simple otp form input field in app.component.ts
and app.component.html
.
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import { Component, VERSION } from "@angular/core"; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; import { NgxOtpInputConfig } from "ngx-otp-input"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { otpForm: FormGroup; otpInputConfig: NgxOtpInputConfig = { otpLength: 6, autofocus: true, classList: { inputBox: "my-super-box-class", input: "my-super-class", inputFilled: "my-super-filled-class", inputDisabled: "my-super-disable-class", inputSuccess: "my-super-success-class", inputError: "my-super-error-class" } }; constructor( private formBuild: FormBuilder, ) { this.otpForm = this.formBuild.group({ otpField: ['', Validators.required] }); } handeOtpChange(value: string[]): void { // console.log(value); } handleFillEvent(value: string): void { console.log(value); } submitOtpForm() { let otpValue = this.otpForm.get('otpField').value; console.log('******************', otpValue); } } |
app.component.html
1 2 3 4 5 6 7 8 9 10 |
<form [formGroup]="otpForm" (ngSubmit)="submitOtpForm()"> <ngx-otp-input [config]="otpInputConfig" (otpChange)="handeOtpChange($event)" (fill)="handleFillEvent($event)" [formControlName]="otpField" > </ngx-otp-input> <button class="otp-submit-btn">Login</button> </form> |
FULL SOURCE CODE