본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

라디오버튼

원문 보기 위키 갱신

라디오버튼 (RadioButton)

라디오버튼은 표준 라디오 버튼 요소를 확장한 PrimeNG 컴포넌트예요. 내부에 스크린 리더만 인식하는 숨은 네이티브 라디오 버튼을 사용해 접근성을 지원하고, 비활성화, 목록 기반 동적 생성, filled 스타일 같은 다양한 옵션도 제공해요. value와 ngModel로 그룹을 구성하는 방법, 반응형 폼과 템플릿 기반 폼에서의 사용법, 그리고 CSS 클래스와 디자인 토큰을 활용한 테마 커스터마이징까지 문서에서 확인할 수 있어요

출처: 문서

본문

접근성

스크린 리더의 경우 RadioButton 컴포넌트는 내부적으로 스크린 리더에만 보이는 숨겨진 네이티브 라디오 버튼 엘리먼트를 사용해요. 컴포넌트를 설명하는 값은 label 태그에 inputId 프로퍼티를 조합해서 제공하거나, ariaLabelledBy, ariaLabel 프로퍼티를 사용해서 제공할 수 있어요.

비활성화

disabled가 있으면 엘리먼트를 편집하거나 포커스할 수 없어요.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RadioButtonModule } from 'primeng/radiobutton';

@Component({
    template: `
        <div class="card flex justify-center gap-2">
            <p-radiobutton [(ngModel)]="value" [value]="1" [disabled]="true" />
            <p-radiobutton [(ngModel)]="value" [value]="2" [disabled]="true" />
        </div>
    `,
    standalone: true,
    imports: [RadioButtonModule, FormsModule]
})
export class RadiobuttonDisabledDemo {
    value: number = 2;
}

동적

RadioButton은 값 목록을 사용해서 생성할 수 있어요.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RadioButtonModule } from 'primeng/radiobutton';

@Component({
    template: `
        <div class="card flex justify-center">
            <div class="flex flex-col gap-4">
                <div *ngFor="let category of categories" class="field-checkbox">
                    <p-radiobutton [inputId]="category.key" name="category" [value]="category" [(ngModel)]="selectedCategory" />
                    <label [for]="category.key" class="ml-2">{{ category.name }}</label>
                </div>
            </div>
        </div>
    `,
    standalone: true,
    imports: [RadioButtonModule, FormsModule]
})
export class RadiobuttonDynamicDemo implements OnInit {
    selectedCategory: any = null;
    categories: any[];

    ngOnInit() {
        this.selectedCategory = this.categories[1];
    }
}

채움

variant 프로퍼티를 filled로 지정하면 기본 outlined 스타일보다 시각적으로 더 강조된 모습으로 컴포넌트가 표시돼요.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RadioButtonModule } from 'primeng/radiobutton';

@Component({
    template: `
        <div class="card flex justify-center">
            <p-radiobutton [(ngModel)]="checked" variant="filled" />
        </div>
    `,
    standalone: true,
    imports: [RadioButtonModule, FormsModule]
})
export class RadiobuttonFilledDemo {
    checked: boolean = false;
}

그룹

RadioButton은 value와 ngModel 프로퍼티를 사용하는 제어 입력(controlled input)으로 사용돼요.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RadioButtonModule } from 'primeng/radiobutton';

@Component({
    template: `
        <div class="card flex justify-center">
            <div class="flex flex-wrap gap-4">
                <div class="flex items-center">
                    <p-radiobutton name="pizza" value="Cheese" [(ngModel)]="ingredient" inputId="ingredient1" />
                    <label for="ingredient1" class="ml-2">Cheese</label>
                </div>
                <div class="flex items-center">
                    <p-radiobutton name="pizza" value="Mushroom" [(ngModel)]="ingredient" inputId="ingredient2" />
                    <label for="ingredient2" class="ml-2">Mushroom</label>
                </div>
                <div class="flex items-center">
                    <p-radiobutton name="pizza" value="Pepper" [(ngModel)]="ingredient" inputId="ingredient3" />
                    <label for="ingredient3" class="ml-2">Pepper</label>
                </div>
                <div class="flex items-center">
                    <p-radiobutton name="pizza" value="Onion" [(ngModel)]="ingredient" inputId="ingredient4" />
                    <label for="ingredient4" class="ml-2">Onion</label>
                </div>
            </div>
        </div>
    `,
    standalone: true,
    imports: [RadioButtonModule, FormsModule]
})
export class RadiobuttonGroupDemo {
    ingredient!: string;
}

유효하지 않은 상태

invalid 프로퍼티를 사용해서 유효성 검사 실패를 나타내는 invalid 상태를 적용할 수 있고, Angular Forms와 통합할 수도 있어요.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RadioButtonModule } from 'primeng/radiobutton';

@Component({
    template: `
        <div class="card flex justify-center">
            <p-radiobutton [(ngModel)]="value" [invalid]="!value" />
        </div>
    `,
    standalone: true,
    imports: [RadioButtonModule, FormsModule]
})
export class RadiobuttonInvalidDemo {
    value: boolean = false;
}

reactiveforms-doc

RadioButton은 리액티브 폼(reactive forms)과도 함께 사용할 수 있어요. 이 경우 formControlName 프로퍼티를 사용해서 컴포넌트를 폼 컨트롤에 바인딩해요.

import { Component, inject } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MessageModule } from 'primeng/message';
import { RadioButtonModule } from 'primeng/radiobutton';
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-wrap gap-4">
                    @for (category of categories; track category.key) {
                        <div class="flex items-center gap-2">
                            <p-radiobutton formControlName="selectedCategory" name="selectedCategory" [inputId]="category.key" [value]="category" [invalid]="isInvalid('selectedCategory')" />
                            <label [for]="category.key"> {{ category.name }} </label>
                        </div>
                    }
                </div>
                @if (isInvalid('selectedCategory')) {
                    <p-message severity="error" size="small" variant="simple"> At least one ingredient must be selected. </p-message>
                }
                <button pButton severity="secondary" type="submit">
                    <span pButtonLabel>Submit</span>
                </button>
            </form>
        </div>
    `,
    standalone: true,
    imports: [MessageModule, RadioButtonModule, ToastModule, ButtonModule, ReactiveFormsModule],
    providers: [MessageService]
})
export class RadiobuttonReactiveformsDemo {
    private messageService = inject(MessageService);
    messageService = inject(MessageService);
    formSubmitted: boolean = false;
    exampleForm: FormGroup;
    categories: any[];

    constructor() {
        this.exampleForm = this.fb.group({
                    selectedCategory: ['', Validators.required]
                });
    }

    isInvalid(controlName: string) {
        const control = this.exampleForm.get(controlName);
        return control?.invalid && this.formSubmitted;
    }

    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;
        }
    }
}

크기

RadioButton은 기본 크기의 대안으로 small과 large 크기를 제공해요.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RadioButtonModule } from 'primeng/radiobutton';

@Component({
    template: `
        <div class="card flex justify-center">
            <div class="flex flex-wrap gap-4">
                <div class="flex items-center gap-2">
                    <p-radiobutton [(ngModel)]="size" inputId="size_small" name="size" value="Small" size="small" />
                    <label for="size_small" class="text-sm">Small</label>
                </div>
                <div class="flex items-center gap-2">
                    <p-radiobutton [(ngModel)]="size" inputId="size_normal" name="size" value="Normal" />
                    <label for="size_normal">Normal</label>
                </div>
                <div class="flex items-center gap-2">
                    <p-radiobutton [(ngModel)]="size" inputId="size_large" name="size" value="Large" size="large" />
                    <label for="size_large" class="text-lg">Large</label>
                </div>
            </div>
        </div>
    `,
    standalone: true,
    imports: [RadioButtonModule, FormsModule]
})
export class RadiobuttonSizesDemo {
    size: any = false;
}

templatedrivenforms-doc

import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MessageModule } from 'primeng/message';
import { RadioButtonModule } from 'primeng/radiobutton';
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-wrap gap-4">
                    @for (category of categories; track category.name) {
                        <div class="flex items-center gap-2">
                            <p-radiobutton [(ngModel)]="ingredient" [inputId]="category.key" [value]="category" [invalid]="isInvalid(exampleForm)" name="ingredient" />
                            <label [for]="category.key"> {{ category.name }} </label>
                        </div>
                    }
                </div>
                @if (isInvalid(exampleForm)) {
                    <p-message severity="error" size="small" variant="simple"> At least one ingredient must be selected. </p-message>
                }
                <button pButton severity="secondary" type="submit">
                    <span pButtonLabel>Submit</span>
                </button>
            </form>
        </div>
    `,
    standalone: true,
    imports: [MessageModule, RadioButtonModule, ToastModule, ButtonModule, FormsModule],
    providers: [MessageService]
})
export class RadiobuttonTemplatedrivenformsDemo {
    private messageService = inject(MessageService);
    messageService = inject(MessageService);
    formSubmitted: boolean = false;
    ingredient!: any;
    categories: any[];

    isInvalid(form: NgForm) {
        return !this.ingredient && form.submitted;
    }

    onSubmit(form: NgForm) {
        if (!this.isInvalid(form)) {
            this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Form Submitted', life: 3000 });
            form.resetForm();
        }
    }
}

패스 스루 옵션

이름 타입 설명
root PassThroughOption<HTMLDivElement, I> root의 DOM 엘리먼트에 속성을 전달하는 데 사용해요.
input PassThroughOption<HTMLInputElement, I> input의 DOM 엘리먼트에 속성을 전달하는 데 사용해요.
box PassThroughOption<HTMLDivElement, I> box의 DOM 엘리먼트에 속성을 전달하는 데 사용해요.
icon PassThroughOption<HTMLDivElement, I> icon의 DOM 엘리먼트에 속성을 전달하는 데 사용해요.

테마

CSS 클래스

클래스 설명
p-radiobutton 루트 엘리먼트의 클래스 이름이에요.
p-radiobutton-box box 엘리먼트의 클래스 이름이에요.
p-radiobutton-input input 엘리먼트의 클래스 이름이에요.
p-radiobutton-icon icon 엘리먼트의 클래스 이름이에요.

디자인 토큰

Token CSS Variable Description
radiobutton.width --p-radiobutton-width 루트의 너비
radiobutton.height --p-radiobutton-height 루트의 높이
radiobutton.background --p-radiobutton-background 루트의 배경
radiobutton.checked.background --p-radiobutton-checked-background 루트의 선택된 상태 배경
radiobutton.checked.hover.background --p-radiobutton-checked-hover-background 루트의 선택된 상태 호버 배경
radiobutton.disabled.background --p-radiobutton-disabled-background 루트의 비활성화 상태 배경
radiobutton.filled.background --p-radiobutton-filled-background 루트의 채워진 상태 배경
radiobutton.border.color --p-radiobutton-border-color 루트의 테두리 색상
radiobutton.hover.border.color --p-radiobutton-hover-border-color 루트의 호버 테두리 색상
radiobutton.focus.border.color --p-radiobutton-focus-border-color 루트의 포커스 테두리 색상
radiobutton.checked.border.color --p-radiobutton-checked-border-color 루트의 선택된 상태 테두리 색상
radiobutton.checked.hover.border.color --p-radiobutton-checked-hover-border-color 루트의 선택된 상태 호버 테두리 색상
radiobutton.checked.focus.border.color --p-radiobutton-checked-focus-border-color 루트의 선택된 상태 포커스 테두리 색상
radiobutton.checked.disabled.border.color --p-radiobutton-checked-disabled-border-color 루트의 선택된 상태 비활성화 테두리 색상
radiobutton.invalid.border.color --p-radiobutton-invalid-border-color 루트의 유효하지 않은 상태 테두리 색상
radiobutton.shadow --p-radiobutton-shadow 루트의 그림자
radiobutton.focus.ring.width --p-radiobutton-focus-ring-width 루트의 포커스 링 너비
radiobutton.focus.ring.style --p-radiobutton-focus-ring-style 루트의 포커스 링 스타일
radiobutton.focus.ring.color --p-radiobutton-focus-ring-color 루트의 포커스 링 색상
radiobutton.focus.ring.offset --p-radiobutton-focus-ring-offset 루트의 포커스 링 오프셋
radiobutton.focus.ring.shadow --p-radiobutton-focus-ring-shadow 루트의 포커스 링 그림자
radiobutton.transition.duration --p-radiobutton-transition-duration 루트의 전환 지속 시간
radiobutton.sm.width --p-radiobutton-sm-width 루트의 Sm 너비
radiobutton.sm.height --p-radiobutton-sm-height 루트의 Sm 높이
radiobutton.lg.width --p-radiobutton-lg-width 루트의 Lg 너비
radiobutton.lg.height --p-radiobutton-lg-height 루트의 Lg 높이
radiobutton.icon.size --p-radiobutton-icon-size 아이콘의 크기
radiobutton.icon.checked.color --p-radiobutton-icon-checked-color 아이콘의 선택된 상태 색상
radiobutton.icon.checked.hover.color --p-radiobutton-icon-checked-hover-color 아이콘의 선택된 상태 호버 색상
radiobutton.icon.disabled.color --p-radiobutton-icon-disabled-color 아이콘의 비활성화 상태 색상
radiobutton.icon.sm.size --p-radiobutton-icon-sm-size 아이콘의 Sm 크기
radiobutton.icon.lg.size --p-radiobutton-icon-lg-size 아이콘의 Lg 크기

더 알아보기 (Learn more)

이 문서에는 원문에서 추출한 별도의 관련 문서 링크가 없어요.