Angular 체크박스 컴포넌트 개요

    Angular Checkbox는 표준 HTML 입력 유형 체크박스의 확장으로, 애니메이션 및 Material Design 스타일과 같은 것들로 강화된 유사한 기능을 제공합니다. 사용자가 주로 양식 및 설문 조사에서 하나 또는 여러 개의 미리 정의된 옵션을 선택할 수 있도록 합니다.

    Ignite UI for Angular는 사용자가 특정 조건에 대해 이진 선택을 할 수 있는 선택 컨트롤입니다. 네이티브 브라우저 체크박스와 비슷하게 동작합니다. 제공하는 기능 중 일부는 스타일 옵션, 테마, 체크됨, 체크되지 않음, 불확정 상태 등입니다.

    Angular 체크박스 예제

    아래의 Angular Checkbox 예제에서 체크박스가 실제로 어떻게 동작하는지 확인하세요.

    EXAMPLE
    TS
    HTML
    SCSS

    이 샘플이 마음에 드시나요? 전체 Ignite UI for Angular 툴킷에 액세스하고 몇 분 안에 나만의 앱을 구축해 보세요. 무료로 다운로드하세요.

    Ignite UI for Angular 확인란 시작하기

    Ignite UI for Angular Checkbox 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.

    ng add igniteui-angular
    cmd

    Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.

    다음 단계는 IgxCheckboxModule에서 app.module.ts 파일:

    // app.module.ts
    
    import { IgxCheckboxModule } from 'igniteui-angular';
    // import { IgxCheckboxModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxCheckboxModule],
        ...
    })
    export class AppModule {}
    typescript

    또는 16.0.0부터 IgxCheckboxComponent 독립형 종속성으로 가져올 수 있습니다.

    // home.component.ts
    
    import { IgxCheckboxComponent } from 'igniteui-angular';
    // import { IgxCheckboxComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-checkbox [checked]="true">
            Simple checkbox
        </igx-checkbox>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IgxCheckboxComponent]
    })
    export class HomeComponent {}
    typescript

    이제 Ignite UI for Angular Checkbox 모듈 또는 구성 요소를 가져왔으므로 구성 요소를 사용할 igx-checkbox 수 있습니다.

    Angular 체크박스 컴포넌트 사용

    데모에서 확인란을 만들려면 구성요소 템플릿 내에 다음 코드를 추가하세요.

    <igx-checkbox [checked]="true">
        Simple checkbox
    </igx-checkbox>
    html

    체크박스 속성

    체크박스 속성을 일부 데이터에 바인딩하여 위의 코드를 개선해 보겠습니다. 각각 설명과 완료라는 두 가지 속성을 갖는 작업 개체의 배열이 있다고 가정해 보겠습니다. 체크박스 구성 요소의 checked 속성을 기본 작업 개체 완료 속성에 바인딩할 수 있습니다. 유사하게 value 속성을 설명에 바인딩할 수 있습니다. 선택적으로 change 이벤트를 바인딩하고 제공된 이벤트 핸들러 메서드에 일부 사용자 지정 논리를 추가할 수도 있습니다.

    // tasks.component.ts
    @Component({...})
    export class HomeComponent {
        public tasks = [
            { done: true, description: 'Research' },
            { done: true, description: 'Implement' },
            { done: false, description: 'Test' }
        ];
    
        public statusChanged() {
            // event handler logic
        }
    }
    typescript

    각 작업에 대한 확인란을 추가한 다음 해당 속성 바인딩을 설정하여 구성 요소 템플릿을 향상합니다.

    <!--tasks.component.html-->
    <igx-checkbox *ngFor="let task of tasks" [checked]="task.done">
        {{ task.description }}
    </igx-checkbox>
    html

    몇 가지 스타일을 추가하세요.

    //task.component.scss
    :host {
        display: flex;
        flex-flow: column nowrap;
        padding: 16px;
    }
    igx-checkbox {
        margin-top: 16px;
    }
    scss

    최종 결과는 다음과 같습니다.

    EXAMPLE
    TS
    HTML
    SCSS

    라벨 위치 지정

    확인란의 labelPosition 속성을 사용하여 라벨의 위치를 지정할 수 있습니다.

    <igx-checkbox labelPosition="before"></igx-checkbox>
    html

    labelPosition이 설정되지 않은 경우 레이블은 확인란 뒤에 배치됩니다.

    Angular의 불확정 체크박스

    선택됨 및 선택 취소됨 상태 외에도 확인란의 세 번째 상태인 불확정이 있습니다. 이 상태에서는 확인란이 선택되거나 선택 취소되지 않습니다. 이는 체크박스의 indeterminate 속성을 사용하여 설정됩니다.

    <igx-checkbox [indeterminate]="true"></igx-checkbox>
    html

    우리는 해야 할 작업 목록과 모든 작업이 완료되었을 때만 체크되는 Angular의 마스터 체크박스가 있는 앱을 만들 수 있습니다. 이전 샘플을 업데이트해 보겠습니다. 템플릿부터 시작하겠습니다.

    <!-- app.component.html -->
    <igx-checkbox
        [readonly]="true"
        [(ngModel)]="masterCheckbox.checked"
        [(indeterminate)]="masterCheckbox.indeterminate"
        (click)="toggleAll()"
    >
    All done
    </igx-checkbox>
    <igx-checkbox class="tasks" *ngFor="let task of tasks" [(ngModel)]="task.done">
        {{ task.description }}
    </igx-checkbox>
    html

    다음으로 하위 작업을 들여쓰기하여 하위 작업이 동일한 그룹에 속해 있다는 것을 더욱 시각적으로 보여줍니다.

    // app.component.scss
    :host {
        display: flex;
        flex-flow: column nowrap;
        padding: 16px;
    }
    igx-checkbox {
        margin-top: 16px;
    }
    igx-checkbox.tasks {
        padding-left: 10px;
    }
    scss

    마지막으로 애플리케이션의 논리를 생성합니다.

    // app.component.ts
    public tasks = [
        { done: true, description: 'Research' },
        { done: true, description: 'Implement' },
        { done: false, description: 'Test' }
    ];
    public get masterCheckbox() {
        return this.tasks.reduce(
            (acc, curr, idx, arr) => {
                acc.checked = acc.checked && curr.done;
                acc.done = curr.done ? acc.done + 1 : acc.done;
                acc.indeterminate = acc.done === arr.length ? false : !!acc.done;
                return acc;
            },
            {
                checked: true,
                done: 0,
                indeterminate: false
            }
        );
    }
    public toggleAll() {
        if (this.masterCheckbox.checked) {
            for (const task of this.tasks) {
                task.done = false;
            }
        } else {
            for (const task of this.tasks) {
                task.done = true;
            }
        }
    }
    ts

    모든 작업이 완료되면 애플리케이션은 다음과 같아야 합니다.

    EXAMPLE
    TS
    HTML
    SCSS

    스타일링

    체크박스 스타일을 시작하려면 모든 테마 기능과 구성 요소 믹스인이 있는 index 파일을 가져와야 합니다.

    @use "igniteui-angular/theming" as *;
    
    // IMPORTANT: Prior to Ignite UI for Angular version 13 use:
    // @import '~igniteui-angular/lib/core/styles/themes/index';
    scss

    그런 다음 checkbox-theme 확장하고 해당 매개변수 중 일부를 사용하여 체크박스 항목의 스타일을 지정하는 새 테마를 만듭니다.

    // in styles.scss
    $custom-checkbox-theme: checkbox-theme(
      $border-radius: 10px,
      $label-color: #011627,
      $empty-color: #ECAA53,
      $fill-color: #ECAA53,
      $tick-color: #011627,
    );
    scss

    마지막 단계는 애플리케이션에 구성 요소 테마를 포함하는 것입니다.

    @include css-vars($custom-checkbox-theme);
    scss

    데모

    EXAMPLE
    TS
    HTML
    SCSS

    App Builder | CTA 배너

    API 참조

    테마 종속성

    추가 리소스

    우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.