UNPKG

angular7-pincode

Version:

a simple directive for otp input template like on mobile otp input template

122 lines (116 loc) 3.71 kB
import { EventEmitter, Component, ViewEncapsulation, ViewChildren, Output, Input, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; class Angular7PincodeComponent { constructor() { this.onFullFill = new EventEmitter(); this.size = 4; this.class = ""; this.isOnlyNumeric = false; this.pin = []; this.pinCode = ""; this.currentIndex = 0; } ngOnInit() { if (this.isOnlyNumeric) { this.otpRegex = new RegExp(/[0-9]/); } else { this.otpRegex = new RegExp(/[a-zA-Z0-9]/); } this.getPin(); } getPin() { for (let i = 0; i < this.size; i++) { this.pin.push(""); } } onKeyUp(event, index) { let key = event.keyCode || event.which; if (!this.otpRegex.test(event.key)) { event.preventDefault(); this.pin[index] = ""; return false; } if (key !== 8 && index != this.size - 1) { this.currentIndex = index + 1; setTimeout(() => { this.allOtpInputs.toArray()[index + 1].nativeElement.focus(); }, 100); } this.pinCode = this.pin.join(''); if (this.pinCode.length == this.size) { setTimeout(() => { this.onFullFill.emit(this.pinCode); }); } } onKeyDown(event, index) { let key = event.keyCode || event.which; if (key === 8 && index != 0) { setTimeout(() => { this.currentIndex = index - 1; }, 10); setTimeout(() => { this.allOtpInputs.toArray()[index - 1].nativeElement.focus(); this.onFullFill.emit(null); }, 100); } } trackByFn(index) { return index; } } Angular7PincodeComponent.decorators = [ { type: Component, args: [{ selector: 'angular7-pincode', template: ` <div class="otp-container"> <input class="otp-input {{class}}" *ngFor="let pininput of pin;let i = index;trackBy: trackByFn" #otpInput name='otpInput{{i}}' [(ngModel)]="pin[i]" autocomplete='off' maxlength="1" [disabled]="currentIndex!=i" (keyup)="onKeyUp($event,i)" (keydown)="onKeyDown($event,i)"/> </div> `, encapsulation: ViewEncapsulation.None, styles: [` .otp-container{ width:100%; text-align:left; } .otp-input{ padding: 5px; margin: 0px; border: 1px solid #ddd; border-right: none; text-align: center; max-width:50px; } .otp-input:last-child{ border-right: 1px solid #ddd; } `] },] } ]; Angular7PincodeComponent.ctorParameters = () => []; Angular7PincodeComponent.propDecorators = { allOtpInputs: [{ type: ViewChildren, args: ['otpInput',] }], onFullFill: [{ type: Output }], size: [{ type: Input }], class: [{ type: Input }], isOnlyNumeric: [{ type: Input }] }; class Angular7PincodeModule { } Angular7PincodeModule.decorators = [ { type: NgModule, args: [{ declarations: [Angular7PincodeComponent], imports: [CommonModule, FormsModule], exports: [Angular7PincodeComponent] },] } ]; /* * Public API Surface of angular7-pincode */ /** * Generated bundle index. Do not edit. */ export { Angular7PincodeComponent, Angular7PincodeModule }; //# sourceMappingURL=angular7-pincode.js.map