Angular OTP 입력 컴포넌트
Angular OTP 입력 컴포넌트 (Input Otp)
InputOtp는 일회용 비밀번호(OTP)를 입력할 때 사용하는 컴포넌트예요 ngModel로 양방향 바인딩하는 게 기본 사용법이고 length 속성으로 글자 수를 정할 수 있는데 기본값은 4예요 integerOnly 옵션을 쓰면 정수만 입력받고 mask 옵션을 쓰면 입력값이 가려져요 크기 조절과 템플릿 커스터마이징도 가능하고 반응형 폼과 템플릿 기반 폼을 모두 지원하니까 프로젝트 상황에 맞게 활용하면 돼요
출처: 문서
본문
접근성
스크린 리더 Input OTP는 InputText 컴포넌트 집합을 사용해요. 스크린 리더 지원에 대한 자세한 정보는 InputText 컴포넌트를 참고하세요.
기본
양방향 값 바인딩은 ngModel을 사용해 정의해요. 문자 개수는 length 프로퍼티로 정의하며, 기본값은 4예요.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { InputOtpModule } from 'primeng/inputotp';
@Component({
template: `
<div class="card flex justify-center">
<p-inputotp [(ngModel)]="value" />
</div>
`,
standalone: true,
imports: [InputOtpModule, FormsModule]
})
export class InputotpBasicDemo {
value: any;
}
정수 전용
integerOnly가 설정되어 있으면 정수만 입력으로 받을 수 있어요.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { InputOtpModule } from 'primeng/inputotp';
@Component({
template: `
<div class="card flex justify-center">
<p-inputotp [(ngModel)]="value" [integerOnly]="true" />
</div>
`,
standalone: true,
imports: [InputOtpModule, FormsModule]
})
export class InputotpIntegeronlyDemo {
value: any;
}
마스크
입력 필드의 값을 가리려면 mask 옵션을 활성화하세요.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { InputOtpModule } from 'primeng/inputotp';
@Component({
template: `
<div class="card flex justify-center">
<p-inputotp [(ngModel)]="value" [mask]="true" />
</div>
`,
standalone: true,
imports: [InputOtpModule, FormsModule]
})
export class InputotpMaskDemo {
value: any;
}
reactiveforms-doc
InputOtp는 리액티브 폼과도 함께 사용할 수 있어요. 이 경우 formControlName 프로퍼티를 사용해 컴포넌트를 폼 컨트롤에 바인딩해요.
import { Component, inject } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { InputOtpModule } from 'primeng/inputotp';
import { MessageModule } from 'primeng/message';
import { ToastModule } from 'primeng/toast';
import { ButtonModule } from 'primeng/button';
import { MessageService } from 'primeng/api';
@Component({
template: `
<p-toast />
<div class="card flex justify-center">
<form [formGroup]="exampleForm" (ngSubmit)="onSubmit()" class="flex flex-col gap-4">
<div class="flex flex-col gap-1">
<p-inputotp formControlName="value" [invalid]="isInvalid('value')" />
@if (isInvalid('value')) {
<p-message severity="error" size="small" variant="simple">Passcode is required.</p-message>
}
</div>
<button pButton severity="secondary" type="submit"><span pButtonLabel>Submit</span></button>
</form>
</div>
`,
standalone: true,
imports: [InputOtpModule, MessageModule, ToastModule, ButtonModule, ReactiveFormsModule]
})
export class InputotpReactiveformsDemo {
messageService = inject(MessageService);
exampleForm: FormGroup | undefined;
formSubmitted: boolean = false;
constructor() {
this.exampleForm = this.fb.group({
value: ['', [Validators.required, Validators.minLength(4)]]
});
}
onSubmit() {
this.formSubmitted = true;
if (this.exampleForm.valid) {
this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Form is submitted', life: 3000 });
this.exampleForm.reset();
this.formSubmitted = false;
}
}
isInvalid(controlName: string) {
const control = this.exampleForm.get(controlName);
return control?.invalid && (control.touched || this.formSubmitted);
}
}
샘플
템플릿과 추가 요소를 활용한 샘플 UI 구현이에요.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { InputOtpModule } from 'primeng/inputotp';
@Component({
template: `
<div class="card flex justify-center">
<div class="flex flex-col items-center">
<div class="font-bold text-xl mb-2">Authenticate Your Account</div>
<p class="text-muted-color block mb-8">Please enter the code sent to your phone.</p>
<p-inputotp [(ngModel)]="value" [length]="6">
<ng-template #input let-token let-events="events" let-index="index">
<input type="text" [maxLength]="1" (input)="events.input($event)" (keydown)="events.keydown($event)" [attr.value]="token" class="custom-otp-input" />
<div *ngIf="index === 3" class="px-4">
<i class="pi pi-minus"></i>
</div>
</ng-template>
</p-inputotp>
<div class="flex justify-between mt-8 self-stretch">
<p-button label="Resend Code" [link]="true" class="p-0" />
<p-button label="Submit Code" />
</div>
</div>
</div>
`,
standalone: true,
imports: [ButtonModule, InputOtpModule, FormsModule]
})
export class InputotpSampleDemo {
value: any;
}
크기
InputOtp는 기본 크기의 대안으로 small과 large 크기를 제공해요.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { InputOtpModule } from 'primeng/inputotp';
@Component({
template: `
<div class="card flex flex-col items-center gap-4">
<p-inputotp [(ngModel)]="value1" size="small" />
<p-inputotp [(ngModel)]="value2" />
<p-inputotp [(ngModel)]="value3" size="large" />
</div>
`,
standalone: true,
imports: [InputOtpModule, FormsModule]
})
export class InputotpSizesDemo {
value1: any;
value2: any;
value3: any;
}
템플릿
제공되는 이벤트와 속성에 바인딩한 자체 UI 요소로 템플릿을 정의하면 기본 디자인을 대체할 수 있어요.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { InputOtpModule } from 'primeng/inputotp';
@Component({
template: `
<div class="card flex justify-center">
<p-inputotp [(ngModel)]="value">
<ng-template #input let-token let-events="events">
<input class="custom-otp-input" (keydown)="events.keydown($event)" (input)="events.input($event)" type="text" [attr.value]="token" [maxLength]="1" />
</ng-template>
</p-inputotp>
</div>
`,
standalone: true,
imports: [InputOtpModule, FormsModule]
})
export class InputotpTemplateDemo {
value: any;
}
templatedrivenforms-doc
import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { InputOtpModule } from 'primeng/inputotp';
import { MessageModule } from 'primeng/message';
import { ToastModule } from 'primeng/toast';
import { ButtonModule } from 'primeng/button';
import { MessageService } from 'primeng/api';
@Component({
template: `
<p-toast />
<div class="card flex justify-center">
<form #exampleForm="ngForm" (ngSubmit)="onSubmit(exampleForm)" class="flex flex-col gap-4">
<div class="flex flex-col gap-1">
<p-inputotp #otpModel="ngModel" [(ngModel)]="value" [invalid]="otpModel.invalid && (otpModel.touched || exampleForm.submitted)" name="value" required [minlength]="4" />
@if (otpModel.invalid && (otpModel.touched || exampleForm.submitted)) {
<p-message severity="error" size="small" variant="simple">Passcode is required.</p-message>
}
</div>
<button pButton severity="secondary" type="submit"><span pButtonLabel>Submit</span></button>
</form>
</div>
`,
standalone: true,
imports: [InputOtpModule, MessageModule, ToastModule, ButtonModule, FormsModule]
})
export class InputotpTemplatedrivenformsDemo {
messageService = inject(MessageService);
value: any;
onSubmit(form: any) {
if (form.valid) {
this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Form Submitted', life: 3000 });
form.resetForm();
}
}
}
Input Otp
Input Otp는 일회용 비밀번호를 입력하는 데 사용해요.
프로퍼티
| Name | Type | Default | Description |
|---|---|---|---|
| dt | InputSignal | undefined | 컴포넌트의 스코프 디자인 토큰을 정의해요. |
| unstyled | InputSignal | undefined | 컴포넌트를 스타일 없이 렌더링할지 여부를 나타내요. |
| pt | InputSignal | undefined | 컴포넌트 내부의 DOM 요소에 속성을 전달할 때 사용해요. |
| ptOptions | InputSignal | undefined | 컴포넌트의 passthrough(pt) 옵션을 구성할 때 사용해요. |
| required | InputSignalWithTransform<boolean, unknown> | false | 설정한 경우 값이 반드시 있어야 해요. |
| invalid | InputSignalWithTransform<boolean, unknown> | false | 설정하면 컴포넌트가 invalid 상태 스타일을 갖도록 지정해요. |
| disabled | InputSignalWithTransform<boolean, unknown> | false | 설정하면 컴포넌트가 disabled 상태 스타일을 갖도록 지정해요. |
| name | InputSignal | undefined | 설정하면 입력의 이름을 지정해요. |
| readonly | boolean | false | 설정하면 입력 필드가 읽기 전용이 되도록 지정해요. |
| tabindex | number | null | 탭 순서에서의 요소 인덱스예요. |
| length | number | 4 | 초기화할 문자 개수예요. |
| styleClass | string | - | 입력 요소의 스타일 클래스예요. |
| mask | boolean | false | 마스크 패턴이에요. |
| integerOnly | boolean | false | 설정하면 입력 필드가 정수만 받도록 지정해요. |
| autofocus | boolean | false | 설정하면 컴포넌트가 로드 시 자동으로 포커스를 받도록 지정해요. |
| variant | InputSignal<"outlined" | "filled"> | undefined | 컴포넌트의 입력 variant를 지정해요. |
| size | InputSignal<"small" | "large"> | undefined | 컴포넌트의 크기를 지정해요. |
이벤트
| Name | Parameters | Description |
|---|---|---|
| onChange | event: InputOtpChangeEvent | 값이 변경될 때 호출되는 콜백이에요. |
| onFocus | event: Event | 컴포넌트가 포커스를 받을 때 호출되는 콜백이에요. |
| onBlur | event: Event | 컴포넌트가 포커스를 잃을 때 호출되는 콜백이에요. |
템플릿
| Name | Type | Description |
|---|---|---|
| input | TemplateRef | 커스텀 입력 템플릿이에요. |
패스스루 옵션
| Name | Type | Description |
|---|---|---|
| host | PassThroughOption<HTMLElement, I> | 호스트의 DOM 요소에 속성을 전달할 때 사용해요. |
| root | PassThroughOption<HTMLDivElement, I> | 루트의 DOM 요소에 속성을 전달할 때 사용해요. |
| pcInputText | InputTextPassThrough | InputText 컴포넌트에 속성을 전달할 때 사용해요. |
테마
CSS 클래스
| Class | Description |
|---|---|
| p-inputotp | 루트 요소의 클래스 이름이에요. |
| p-inputotp-input | 입력 요소의 클래스 이름이에요. |
디자인 토큰
| Token | CSS Variable | Description |
|---|---|---|
| inputotp.gap | --p-inputotp-gap | 루트의 간격이에요. |
| inputotp.input.width | --p-inputotp-input-width | 입력의 너비예요. |
| inputotp.input.sm.width | --p-inputotp-input-sm-width | 작은 화면에서의 입력 너비예요. |
| inputotp.input.lg.width | --p-inputotp-input-lg-width | 큰 화면에서의 입력 너비예요. |
더 알아보기 (Learn more)
이 문서에는 원문에서 추출한 별도의 관련 문서 링크가 없어요.