Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions angular-code-input/src/lib/code-input.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
[class.empty]="isInputElementEmptyAt(i)"
[class.code-hidden]="isCodeHidden">
<input #input
(paste)="onPaste($event, i)"
(input)="onInput($event, i)"
(keydown)="onKeydown($event, i)"
[type]="inputType"/>
Expand Down
43 changes: 41 additions & 2 deletions angular-code-input/src/lib/code-input.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import {
Component,
ElementRef,
EventEmitter,
Input, OnChanges,
Input,
OnChanges,
OnInit,
Output,
QueryList, SimpleChanges,
QueryList,
SimpleChanges,
ViewChildren
} from '@angular/core';

Expand Down Expand Up @@ -99,6 +101,43 @@ export class CodeInputComponent implements AfterViewInit, OnInit, OnChanges {
this.inputs[next].focus();
}

onPaste(e: ClipboardEvent, i: number): void {
e.preventDefault();
e.stopPropagation();

const data = e.clipboardData?.getData('text');

if (this.isEmpty(data)) {
return;
}

// Convert paste text into iterable
const values = data.split('');
let index = 0;

for (const val of values) {
const target = this.inputs[i + index];

// Cancel the loop when a value cannot be used
if (!this.canInputValue(val)) {
this.setInputValue(target, null);
this.setStateForInput(target, InputState.reset);
return;
}

this.setInputValue(target, val.toString());

// Emit changes when we have reached the last input or we are at the last cycle of our values array
if (i + index + 1 > this.codeLength - 1 || index >= values.length - 1) {
target.blur();
this.emitChanges();
return;
}

index += 1;
}
}

async onKeydown(e: any, i: number): Promise<void> {
const target = e.target;
const isTargetEmpty = this.isEmpty(target.value);
Expand Down