Search code examples
angularionic-frameworkionic4

How to store variables of OTP Controller inputs?


I am trying to get the values of the 6 otp controller inputs so, I added the ngModel to each ion-input in the otp controller. Then I am concatenating all the properties to one property but it is not working for me.

page.html

  <ion-grid>
              <ion-row text-center>
                <ion-col ngDefaultControl>
                  <ion-input [(ngModel)]="password1" #otp1 required maxLength="1" 
     (keyup)="otpController($event,otp2,'')">
                  </ion-input>
                  <ion-input [(ngModel)]="password2" #otp2 required maxLength="1" 
     (keyup)="otpController($event,otp3,otp1)">
                  </ion-input>
                  <ion-input [(ngModel)]="password3" #otp3 required maxLength="1" 
     (keyup)="otpController($event,otp4,otp2)">
                  </ion-input>
                  <ion-input [(ngModel)]="password4" #otp4  required maxLength="1" 
     (keyup)="otpController($event,otp5,otp3)">
                  </ion-input>
                  <ion-input [(ngModel)]="password5" #otp5 required maxLength="1" 
    (keyup)="otpController($event,otp6,otp4)">
                   </ion-input>
                   <ion-input [(ngModel)]="password6" #otp6  required maxLength="1" 
     (keyup)="otpController($event,'',otp5)">
                   </ion-input>
                 </ion-col>
                </ion-row>
        </ion-grid>

page.ts

export class Page {
password: any;
password1:any;
password2:any;
password3:any;
password4:any;
password5:any;
password6:any;
  constructor() { }
changer(){
  this.password = this.password1 + this.password2 + this.password3 + this.password4 + this.password5 + this.password6
}

Solution

  • you can achive this using library it's very easily u can get

    npm i ng-otp-input

    in html

    <ng-otp-input #ngOtpInput (onInputChange)="onOtpChange($event)" 
    *ngIf="showOtpComponent" [config]="config"></ng-otp-input>
    
    //for seeing otp
    <span *ngIf="otp" class="o-t-p">Entered otp :-{{otp}}</span>
    

    in ts

    otp: string;
      showOtpComponent = true;
      @ViewChild('ngOtpInput') ngOtpInput: any;
    
      onOtpChange(otp) {
        this.otp = otp;
      }
    
      setVal(val) {
        this.ngOtpInput.setValue(val);
      }
    

    complete exmple

    https://stackblitz.com/github/code-farmz/ng-otp-input?file=src%2Fapp%2Fapp.component.ts

    for more information https://www.npmjs.com/package/ng-otp-input