Skip to content

Commit 845f5ae

Browse files
committed
Adding property for focusing on the last input when the code is filled fully
1 parent a4c3843 commit 845f5ae

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

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

+1
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+
(click)="onClick($event)"
56
(paste)="onPaste($event, i)"
67
(input)="onInput($event, i)"
78
(keydown)="onKeydown($event, i)"

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

+35-5
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export class CodeInputComponent implements AfterViewInit, OnInit, OnChanges {
3030
@Input() readonly isNonDigitsCode = false;
3131
@Input() readonly isCodeHidden = false;
3232
@Input() readonly isPrevFocusableAfterClearing = true;
33+
@Input() readonly isFocusingOnLastByClickIfFilled = false;
3334
@Input() readonly inputType = 'tel';
3435
@Input() readonly code?: string | number;
3536

@@ -72,6 +73,29 @@ export class CodeInputComponent implements AfterViewInit, OnInit, OnChanges {
7273
* Methods
7374
*/
7475

76+
onClick(e: any): void {
77+
// handle click events only if the the prop is enabled
78+
if (!this.isFocusingOnLastByClickIfFilled) {
79+
return;
80+
}
81+
82+
const target = e.target;
83+
const last = this.inputs[this.codeLength - 1];
84+
// already focused
85+
if (target === last) {
86+
return;
87+
}
88+
89+
// check filling
90+
const isFilled = this.getCurrentFilledCode().length >= this.codeLength;
91+
if (!isFilled) {
92+
return;
93+
}
94+
95+
// focusing on the last input if is filled
96+
setTimeout(() => last.focus());
97+
}
98+
7599
onInput(e: any, i: number): void {
76100
const next = i + 1;
77101
const target = e.target;
@@ -205,6 +229,16 @@ export class CodeInputComponent implements AfterViewInit, OnInit, OnChanges {
205229
}
206230

207231
private emitCode(): void {
232+
const code = this.getCurrentFilledCode();
233+
234+
this.codeChanged.emit(code);
235+
236+
if (code.length >= this.codeLength) {
237+
this.codeCompleted.emit(code);
238+
}
239+
}
240+
241+
private getCurrentFilledCode(): string {
208242
let code = '';
209243

210244
for (const input of this.inputs) {
@@ -213,11 +247,7 @@ export class CodeInputComponent implements AfterViewInit, OnInit, OnChanges {
213247
}
214248
}
215249

216-
this.codeChanged.emit(code);
217-
218-
if (code.length >= this.codeLength) {
219-
this.codeCompleted.emit(code);
220-
}
250+
return code;
221251
}
222252

223253
private isBackspaceKey(e: any): Promise<boolean> {

0 commit comments

Comments
 (0)