Skip to content

Commit 04d6b54

Browse files
authored
Merge pull request #5 from AnimaWolf/master
Implement code paste support
2 parents 0378cd0 + b9e7446 commit 04d6b54

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

angular-code-input/src/lib/code-input.component.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
[class.empty]="isInputElementEmptyAt(i)"
33
[class.code-hidden]="isCodeHidden">
44
<input #input
5+
(paste)="onPaste($event, i)"
56
(input)="onInput($event, i)"
67
(keydown)="onKeydown($event, i)"
78
[type]="inputType"/>

angular-code-input/src/lib/code-input.component.ts

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@ import {
33
Component,
44
ElementRef,
55
EventEmitter,
6-
Input, OnChanges,
6+
Input,
7+
OnChanges,
78
OnInit,
89
Output,
9-
QueryList, SimpleChanges,
10+
QueryList,
11+
SimpleChanges,
1012
ViewChildren
1113
} from '@angular/core';
1214

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

104+
onPaste(e: ClipboardEvent, i: number): void {
105+
e.preventDefault();
106+
e.stopPropagation();
107+
108+
const data = e.clipboardData?.getData('text');
109+
110+
if (this.isEmpty(data)) {
111+
return;
112+
}
113+
114+
// Convert paste text into iterable
115+
const values = data.split('');
116+
let index = 0;
117+
118+
for (const val of values) {
119+
const target = this.inputs[i + index];
120+
121+
// Cancel the loop when a value cannot be used
122+
if (!this.canInputValue(val)) {
123+
this.setInputValue(target, null);
124+
this.setStateForInput(target, InputState.reset);
125+
return;
126+
}
127+
128+
this.setInputValue(target, val.toString());
129+
130+
// Emit changes when we have reached the last input or we are at the last cycle of our values array
131+
if (i + index + 1 > this.codeLength - 1 || index >= values.length - 1) {
132+
target.blur();
133+
this.emitChanges();
134+
return;
135+
}
136+
137+
index += 1;
138+
}
139+
}
140+
102141
async onKeydown(e: any, i: number): Promise<void> {
103142
const target = e.target;
104143
const isTargetEmpty = this.isEmpty(target.value);

0 commit comments

Comments
 (0)