Angular Checkbox 구성 요소 개요

    Angular Checkbox는 표준 HTML 입력 유형 확인란의 확장으로 유사한 기능을 제공하며 애니메이션 및 머티리얼 디자인 스타일과 같은 기능만 향상되었습니다. 이를 통해 사용자는 주로 양식 및 설문 조사에서 하나 이상의 사전 정의된 옵션을 선택할 수 있습니다.

    Ignite UI for Angular 사용자가 특정 조건에 대해 이진 선택을 할 수 있는 선택 컨트롤입니다. 이는 기본 브라우저 확인란과 유사하게 작동합니다. 제공되는 기능 중 일부는 스타일 옵션, 테마, 선택됨, 선택 취소됨, 불확정 상태 등입니다.

    Angular Checkbox Example

    아래의 Angular Checkbox 예제에서 체크박스가 실제로 작동하는 모습을 확인하세요.

    Getting Started with Ignite UI for Angular Checkbox

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

    ng add igniteui-angular
    

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

    또는 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 {}
    

    이제 Ignite UI for Angular 가져왔으므로 igx-checkbox 구성 요소 사용을 시작할 수 있습니다.

    Using the Angular Checkbox Component

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

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

    Checkbox properties

    체크박스 속성을 일부 데이터에 바인딩하여 위의 코드를 개선해 보겠습니다. 각각 설명과 완료라는 두 가지 속성을 갖는 작업 개체의 배열이 있다고 가정해 보겠습니다. 체크박스 구성 요소의 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
        }
    }
    

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

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

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

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

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

    Label Positioning

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

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

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

    Indeterminate Checkbox in Angular

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

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

    수행해야 할 작업 목록과 모든 작업이 완료된 경우에만 확인되는 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>
    

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

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

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

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

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

    Angular Checkbox Styling

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

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

    그런 다음 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,
    );
    

    Including Themes

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

    $legacy-support​ ​true로 설정된 경우 다음과 같은 구성 요소 테마를 포함합니다.

     @include checkbox($custom-checkbox-theme);
    
    Note

    구성 요소가 Emulated ViewEncapsulation을 사용하는 경우::ng-deep 사용하여 이 캡슐화를 penetrate 해야 합니다.

    :host {
         ::ng-deep {
            @include checkbox($custom-checkbox-theme);
        }
    }
    

    $legacy-support​ ​false (기본값)로 설정된 경우 다음과 같은 구성 요소 CSS 변수를 포함합니다.

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

    구성 요소가 Emulated ViewEncapsulation을 사용하는 경우 변수를 재정의하려면 전역 선택기가 필요하므로 여전히:host 사용해야 합니다.

    :host {
        @include css-vars($custom-checkbox-theme);
    }
    

    Demo

    API References

    Theming Dependencies

    Additional Resources

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