Angular Select 컴포넌트 개요

    Angular Select는 미리 정의된 값 목록에서 단일 값을 선택하는 데 사용되는 폼 구성 요소입니다. Angular Select 구성 요소는 기본 HTML select 요소와 동일한 기능을 제공하지만 훨씬 더 많은 사용자 지정 옵션을 제공합니다. IgxDropDownComponent를 기반으로 하며 템플릿, 가상화 및 드롭다운 목록 항목 사용자 지정을 포함한 모든 기능을 지원합니다.

    Angular Select Example

    아래는 기본적인 Angular Select 예시입니다. 클릭당 열리는 여러 선택 사항 목록을 표시하는 간단한 상황별 메뉴가 있습니다.

    Getting Started with Ignite UI for Angular Select

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

    ng add igniteui-angular
    

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

    다음 단계는 다음 단계를 가져오는 것입니다.IgxSelectModule 안에 app.module.ts 파일.

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

    또는16.0.0 독립 실행형 의존성으로 가져오IgxSelectComponent 거나, 토큰을IGX_SELECT_DIRECTIVES 사용해 컴포넌트와 그 지원 컴포넌트, 명령어를 가져올 수도 있습니다.

    // home.component.ts
    
    import { FormsModule } from '@angular/forms';
    import { IGX_SELECT_DIRECTIVES } from 'igniteui-angular/select';
    // import { IGX_SELECT_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-select [(ngModel)]="selected">
            <label igxLabel>Simple Select</label>
            <igx-select-item value="Orange">Orange</igx-select-item>
            <igx-select-item value="Apple">Apple</igx-select-item>
            <igx-select-item value="Banana">Banana</igx-select-item>
            <igx-select-item value="Mango">Mango</igx-select-item>
        </igx-select>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_SELECT_DIRECTIVES, FormsModule]
        /* or imports: [IgxSelectComponent, IgxSelectItemComponent, IgxLabelDirective, FormsModule] */
    })
    export class HomeComponent {
        public selected: string;
    }
    

    이제 Ignite UI for Angular Select 모듈이나 디렉티브를 가져왔으니, 컴포넌트를igx-select 사용할 수 있습니다.

    Using the Angular Select

    선택할 수 있는 항목 목록과 함께 추가igx-select 하세요. 우리는 그igx-select-itemigx-select 안에 담긴 물건들을 진열합니다.

    <igx-select>
        <label igxLabel>Simple Select</label>
        <igx-select-item value="Orange">Orange</igx-select-item>
        <igx-select-item value="Apple">Apple</igx-select-item>
        <igx-select-item value="Banana">Banana</igx-select-item>
        <igx-select-item value="Mango">Mango</igx-select-item>
    </igx-select>
    

    또 다른 방법은 *ngFor 구조 지시문을 사용하여 표시하려는 항목 컬렉션을 사용하는 것입니다.

    public items: string[] = ['Orange', 'Apple', 'Banana', 'Mango'];
    
    <igx-select [(ngModel)]="selected">
        <label igxLabel>Simple Select</label>
        <igx-select-item *ngFor="let item of items" [value]="item">
            {{item}}
        </igx-select-item>
    </igx-select>
    

    기본적으로 Select 컴포넌트는 입력 필드에서 아이템 요소의 를innerText 사용합니다. 더 복잡한 항목 템플릿의 경우, 이 항목이 선택되었을 때 입력 필드에 무엇을 표시할지 명시적으로 설정할text 수 있습니다. 예를 들어:

    <igx-select>
        <igx-select-item *ngFor="let item of items" [value]="item.value" [text]="item.text">
            {{item.text}} ( {{item.count}} )
        </igx-select-item>
    </igx-select>
    

    좀 더 정교한 아이템 템플릿으로 이 속성을 확인text 하려면 '그룹으로 선택' 섹션 아래 그룹화 샘플을 확인해 보세요.

    Input Properties

    Select 구성 요소는 입력 그룹에 적용할 수 있는 다음 지시문을 지원합니다.

    • igxLabel- 속성을 설정할for 필요가 없으며, Angular Select 입력과의 링크는 자동으로 처리됩니다.aria-labelledby
    • igx-prefix/igxPrefix
    • igx-suffix/igxSuffix- 내장된 토글 버튼 접미사는 항상 마지막에 표시됩니다.
    • igx-hint/igxHint
    <igx-select [(ngModel)]="selected">
        <label igxLabel>Pick a fruit</label>
        <igx-prefix>
            <span class="bio-prefix">BIO</span>
        </igx-prefix>
        <igx-suffix *ngIf="selected">
            <igx-icon (click)="clearSelection($event)">clear</igx-icon>
        </igx-suffix>
        <igx-hint>Choose a banana</igx-hint>
        <igx-select-item *ngFor="let item of items" [value]="item">
            {{item}}
        </igx-select-item>
    </igx-select>
    

    Note

    Select 컴포넌트에 NOplaceholder가 지정되어 있고 선택이 이루어지지 않으면, 플레이igxLabel 스홀더가 있을 것으로 예상되는 위치에 전환되어 나타납니다.

    Group Select Items

    항목 그룹을 시각적으로 구분하기 위해 select 컴포넌트는 항목을<igx-select-item-group> 감싸서 그룹화하는 기능을 지원합니다. 이 방법은 구성 요소를 선언하기 위해 반복할 수 있는 계층적 데이터에서 가장 잘 작동합니다. 다음 예시에서 각 그룹은 와label 다음과 같은 집합items을 가집니다:

    public greengrocery: Array<{ label: string, items: Array<{ type: string, origin: string }> }> = [
        { label: 'Fruits', items: [
                { type: 'Apple', origin: 'local' },
                { type: 'Orange', origin: 'import' },
                { type: 'Banana', origin: 'import'}
            ]
        },
        { label: 'Vegetables', items: [
                { type: 'Cucumber', origin: 'local' },
                { type: 'Potato', origin: 'import' },
                { type: 'Pepper', origin: 'local' }
            ]
        }
    ];
    

    그런 다음 템플릿 파일에서 객체를 반복하고 그에 따라 해당 항목에 액세스할 수 있습니다.

    <igx-select #select>
        <label igxLabel>Select With Groups</label>
        <igx-select-item-group *ngFor="let group of greengrocery" [label]="group.label">
            <igx-select-item *ngFor="let item of group.items" [value]="item.type" [text]="item.type">
                {{item.type}}
                <igx-icon
                    title="Local product"
                    *ngIf="item.origin === 'local'; else templateImport"
                >local_shipping</igx-icon>
                <ng-template #templateImport>
                    <igx-icon title="Import product">flight</igx-icon>
                </ng-template>
            </igx-select-item>
        </igx-select-item-group>
    </igx-select>
    

    현재 Select 컴포넌트에는 기본 헤더 및 풋 템플릿이 없습니다. 하지만 헤더나 푸터 템플릿을 각각igxSelectHeaderigxSelectFooter 또는 표시하여 추가할 수 있습니다. 이 템플릿들은 커스텀 템플릿이므로, 스타일링도 정의해야 합니다. 이 예시에서는 헤더와 푸터 ng-템플릿이 모두 정의되어 있습니다. 헤더에는 기본적인 필터링이 구현된 VIAigx-buttongroup가 있습니다. 푸터에는 전달 방법에 따른 모든 아이템의 정적 요약이 포함되어 있습니다.

    <igx-select>
        <label igxLabel>Pick your fruit</label>
        <igx-select-item *ngFor="let fruit of fruits" [value]="fruit.type" [text]="fruit.type" [ngSwitch]="fruit.delivery">
            {{fruit.type}}
            <igx-icon *ngSwitchCase="'flight'">flight</igx-icon>
            <igx-icon *ngSwitchCase="'train'">train</igx-icon>
            <igx-icon *ngSwitchCase="'boat'">directions_boat</igx-icon>
        </igx-select-item>
        <ng-template igxSelectHeader>
            <div class="custom-select-header">
                <span class="sample-template-heading">DELIVERY METHOD</span>
                <igx-buttongroup (click)="filter($event.target.title)">
                        <button igxButton title="flight"><igx-icon title="flight">flight</igx-icon></button>
                        <button igxButton title="train"><igx-icon title="train">train</igx-icon></button>
                        <button igxButton title="boat"><igx-icon title="boat">directions_boat</igx-icon></button>
                </igx-buttongroup>
            </div>
        </ng-template>
        <ng-template igxSelectFooter>
            <div class="custom-select-footer">
                <span class="sample-template-heading">TOTAL</span>
                <div class="sample-template-icons">
                    <span class="sample-template-icons__item">
                        <igx-icon
                            title="flight"
                            [class.important-icon]="selected === 'flight'"
                        >flight</igx-icon>
                        {{flightCount}}
                    </span>
                    <span class="sample-template-icons__item">
                        <igx-icon
                            title="train"
                            [class.important-icon]="selected === 'train'"
                        >train</igx-icon>
                        {{trainCount}}
                    </span>
                    <span class="sample-template-icons__item">
                        <igx-icon
                            title="boat"
                            [class.important-icon]="selected === 'boat'"
                        >directions_boat
                        </igx-icon>
                        {{boatCount}}
                    </span>
                </div>
            </div>
        </ng-template>
    </igx-select>
    

    Custom Toggle Button in Angular Select

    기본 토글 버튼을 명령어로igxSelectToggleIcon 설정하거나 aTemplateRef를 속성에toggleIconTemplate 설정해 맞춤 설정할 수 있습니다.

    <igx-select #select>
        ...
        <ng-template igxSelectToggleIcon let-collapsed>
            <igx-icon>{{ collapsed ? 'add_circle' : 'add_circle_outline'}}</igx-icon>
        </ng-template>
        ...
    <igx-select>
    

    Keyboard Navigation

    • 선택 버튼이 초점이 맞춰진 상태에서 또는 키를 클릭igx-selectSpaceEnter 해 열ALT + Up/Down Arrow 어보세요.
    • igx-selectALT + Up/Down Arrow조합이나EnterSpaceEscTab 어떤 키로든 닫으세요.
    • 키를 사용하면Up/Down Arrow 아이템을 탐색할 수 있습니다.
    • ORHome 키를 사용하면End 목록의 첫 번째와 마지막 항목으로 이동할 수 있습니다.
    • 해당 키를 눌러 특정 문자로 시작하는 목록 항목을 탐색할 수 있습니다.
    • 이동하려는 항목의 처음 몇 글자를 빠르게 입력하여 특정 항목으로 이동할 수 있습니다.
    • 또는Enter 키로Space 항목을 선택합니다
    Note

    igx-select단일 선택된 아이템만 지원합니다.

    또한 드래그 앤 드롭 App Builder ™ 사용하여 특정 프로세스를 자동화하고 다음 Angular 앱을 구축할 때 과도한 수동 코딩의 필요성을 줄이는 방법을 확인할 수 있습니다.

    Custom Overlay Settings

    커스텀OverlaySettings을 만들 수 있습니다. 이를 위해 먼저 템플릿을 다음과 같이 정의하세요:

    <igx-select [overlaySettings]="customOverlaySettings">
        <igx-select-item *ngFor="let item of items">
            {{item}}
        </igx-select-item>
    </igx-select>
    
    • 속성이overlaySettings 사용자 지정 설정에 바인딩된 경우입니다.

    수업 내에는 다음과 같은 내용이 있습니다.

    export class MyClass implements OnInit {
        @ViewChild(IgxSelectComponent)
        public select: IgxSelectComponent;
        public items: string[] = ['Orange', 'Apple', 'Banana', 'Mango', 'Tomato'];
        public customOverlaySettings: OverlaySettings;
    
        public ngOnInit(): void {
            const positionSettings: PositionSettings = {
                closeAnimation: scaleOutBottom,
                horizontalDirection: HorizontalAlignment.Right,
                horizontalStartPoint: HorizontalAlignment.Left,
                openAnimation: scaleInTop,
                verticalDirection: VerticalAlignment.Bottom,
                verticalStartPoint: VerticalAlignment.Bottom
            };
            this.customOverlaySettings = {
                target: this.select.inputGroup.element.nativeElement,
                positionStrategy: new ConnectedPositioningStrategy(
                    positionSettings
                ),
                scrollStrategy: new AbsoluteScrollStrategy()
            };
        }
    }
    

    ConnectedPositioningStrategy에 직접 전달되는 PositionSettings 객체를 생성하는 것을 볼 수 있습니다. 반드시 수행할 필요는 없지만 사용자 정의 위치 지정을 정의하고 싶기 때문에 이를 사용하여 전략의 기본 설정을 재정의합니다.

    • ngOnInit 후크 내부에서 모든 설정을 지정할 수 있으며 이는 구성 요소 생성 시 템플릿에 자동으로 영향을 미칩니다.

    또한 사용자 정의된 OverlaySettings 객체를 IgxSelectComponent의 열기 함수에 전달할 수도 있습니다. 여기서 템플릿은 다음과 같습니다.

    <igx-select>
        <igx-select-item *ngFor="let item of items">
            {{item}}
        </igx-select-item>
    </igx-select>
    
    <button (click)="onClick($event)"></button>
    

    그리고 수업에는 다음이 있습니다.

    export class MyClass implements OnInit {
        /* -- */
        private otherCustomOverlaySettings: OverlaySettings = {
            positionStrategy: new GlobalPositionStrategy(),
            scrollStrategy: new AbsoluteScrollStrategy()
        }
        onClick(event: MouseEvent): void {
            this.select.open(this.otherCustomOverlaySettings)
        }
        /* -- */
    }
    
    Note

    함수와 템플릿 모두에서 인수open로 커스텀 설정을 전달하면,igx-select 함수에open 제공된 값을 사용할 것입니다. 하지만 설정을 내부 이벤트(예:openingopenedigx-select)에 바인딩하면 템플릿에 제공된 설정을 사용할 수 있습니다.

    스타일링

    Select Theme Property Map

    기본 속성을 수정하면 모든 관련 종속 속성이 자동으로 업데이트되어 변경 내용이 반영됩니다.

    기본 속성 종속 속성 설명
    $toggle-버튼-배경
    $toggle-버튼-전경 토글 버튼의 전경 색상
    $toggle 버튼 전경 채우기토글 버튼이 채워졌을 때 전경 색상
    $toggle-버튼-배경-초점초점 시 배경색
    $toggle-버튼-배경-초점--border (부트스트랩/인디고)보더 변형(부트스트랩/인디고)에 집중할 때의 배경
    $toggle 버튼-전경-초점토글 버튼이 초점을 맞췄을 때 전경 색상

    모든 구성 요소에는 고유한 테마 기능이 있습니다.

    Select 컴포넌트에 스타일링을 하려면, 그 안에 포함된 컴포넌트를 스타일링해야 합니다. 우리의 경우, 이들은 입력-그룹-테마드롭다운 테마 입니다. 스타일링 섹션과Input Group 스타일링 섹션을 살펴보Drop Down 면서 이 두 요소를 어떻게 스타일링할지 더 잘 이해할 수 있습니다.

    또한 Select 컴포넌트의 버튼 스타일링에만 사용되는 기능도 있습니다select-theme.
    Select 컴포넌트 버튼 스타일링을 시작하려면, 모든 테마 함수와 컴포넌트 믹스인이 있는 파일을 가져와index야 합니다:

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

    가장 간단한 방법을 따라, 우리는 매개변수select-theme$toggle-button-background 제공하는 새로운 테마를 생성합니다. 테마 기능은 이 단일 값을 기반으로 각 상태별 배경 및 전경 색상을 자동으로 계산합니다.

    $custom-select-theme: select-theme(
      $toggle-button-background: #57a5cd,
    );
    

    마지막 단계는 애플리케이션에 사용자 정의 라디오 테마를 전달하는 것입니다.

    @include css-vars($custom-select-theme);
    

    Styling with Tailwind

    저희의 맞춤형 Tailwind 유틸리티 클래스를 사용해 셀렉트를 스타일링할 수 있습니다. 먼저 Tailwind를 꼭 설정 하세요.

    전역 스타일시트의 순풍 가져오기와 함께 다음과 같이 원하는 테마 유틸리티를 적용할 수 있습니다.

    @import "tailwindcss";
    ...
    @use 'igniteui-theming/tailwind/utilities/material.css';
    

    유틸리티 파일에는 테마 변형 두 가지lightdark 모두 포함되어 있습니다.

    • 라이트 테마에는 클래스를 사용light-* 하세요.
    • 어두운 테마에는 클래스를 사용dark-* 하세요.
    • 접두사 뒤에 컴포넌트 이름을 덧붙이세요,light-selectdark-select 예: .

    이 클래스들이 적용되면 동적 테마 계산이 가능합니다. 그 다음에는 생성된 CSS 변수를 무arbitrary properties 시할 수 있습니다. 콜론 다음에는 유효한 CSS 색상 형식(HEX, CSS 변수, RGB 등)을 입력하세요.

    전체 부동산 목록은 select-theme에서 확인할 수 있습니다. 문법은 다음과 같습니다:

    <igx-select
      class="!light-select ![--toggle-button-background:#99BAA6]">
      ...
    </igx-select>
    
    Note

    느낌표(!)는 유틸리티 클래스가 우선순위가 되도록 보장하기 위해 필요합니다. Tailwind는 레이어에 스타일을 적용하는데, 이 스타일을 중요하게 표시하지 않으면 컴포넌트의 기본 테마에 의해 덮어쓰여집니다.

    마지막에 선택 화면은 다음과 같이 보여야 합니다:

    API Reference

    Theming Dependencies

    Additional Resources

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