Angular ComboBox 구성 요소 개요
Angular ComboBox 구성 요소는 편집 가능한 기능을 제공하는 드롭다운 목록을 나타내며, 사용자는 미리 정의된 목록에서 여러 옵션을 선택할 수 있습니다. Ignite UI for Angular ComboBox 구성 요소는 필터링 기능, 그룹화 및 드롭다운 목록에 사용자 정의 값 추가 기능도 제공합니다. HTML select 태그의 대안으로 사용할 수 있으며 데이터 바인딩(로컬 및 원격), 필터링, 그룹화, 항목에 대한 사용자 정의 템플릿, 헤더 및 푸터, 사용자 정의 값 등과 같은 여러 가지 기본 제공 기능이 있습니다.
Angular ComboBox Example
이 Angular ComboBox 예제에서는 사용자가 제공된 데이터로 항목을 필터링하고 선택을 수행하는 방법을 볼 수 있습니다. 또한 ComboBox는 키보드 탐색 및 사용자 지정 스타일 기능을 노출합니다.
Angular ComboBox Features
콤보박스 컨트롤은 다음 기능을 제공합니다.
Getting Started with Ignite UI for Angular ComboBox
Ignite UI for Angular ComboBox 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.
ng add igniteui-angular
Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.
다음 단계는 다음 단계를 가져오는 것입니다.IgxComboModule 당신의 app.module.ts 파일.
import { IgxComboModule } from 'igniteui-angular/combo';
// import { IgxComboModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
imports: [
...
IgxComboModule,
...
]
})
export class AppModule {}
또는16.0.0 독립 실행형 의존성으로 가져오IgxComboComponent 거나, 토큰을IGX_COMBO_DIRECTIVES 사용해 컴포넌트와 그 지원 컴포넌트, 명령어를 가져올 수도 있습니다.
// home.component.ts
import { IGX_COMBO_DIRECTIVES } from 'igniteui-angular/combo';
// import { IGX_COMBO_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: '<igx-combo></igx-combo>',
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IGX_COMBO_DIRECTIVES]
/* or imports: [IgxComboComponent] */
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Combo module or directives imported, you can start using the igx-combo component.
Using the Angular ComboBox Component
초기 설정 후 igx-combo를 데이터에 바인딩할 수 있습니다.
@Component({
selector: 'app-combo-demo',
template: '<igx-combo [data]="cities"></igx-combo>',
styleUrls: ['combo-demo.component.scss'],
standalone: true,
imports: [IGX_COMBO_DIRECTIVES]
})
export class ComboDemo implements OnInit {
public cities: { name: string, id: string }[] = [];
public ngOnInit() {
this.cities = [{ name: 'London', id: 'UK01' }, { name: 'Sofia', id: 'BG01'}, ...];
}
}
우리의 콤보박스는 이제 도시 배열에 바인딩되었지만 항목의 텍스트에 사용할 속성과 값에 사용할 속성을 구성 요소에 아직 알려주지 않았습니다. 지금 해보자.
Data value and display properties
Since the combobox is bound to an array of complex data (i.e. objects), we need to specify a property that the control will use to handle the selected items. The control exposes two @Input properties - valueKey and displayKey:
valueKey- Optional, recommended for object arrays - Specifies which property of the data entries will be stored for the combobox's selection. IfvalueKeyis omitted, the combobox value will use references to the data entries (i.e. the selection will be an array of entries fromigxCombo.data).displayKey- Required for object arrays - Specifies which property will be used for the items' text. If no value is specified fordisplayKey, the combobox will use the specifiedvalueKey(if any).
In our case, we want the combobox to display the name of each city and the combobox value to store the id of each city. Therefore, we are providing these properties to the combobox's displayKey and valueKey, respectively:
<igx-combo [data]="cities" displayKey="name" valueKey="id"></igx-combo>
Note
When the data source is an array of primitives (e.g. string[], number[]), do not specify a valueKey and displayKey. Primitive values will be used for both value and text.
양방향 바인딩
The combobox component fully supports two-way data-binding with [(ngModel)] as well as usage in template driven and reactive forms. The combobox selection can be accessed either through two-way binding or through the selection API. We can pass an array of items of the same type as the ones in the combobox's selection (based on valueKey) and any time one changes, the other is updated accordingly.
In the following example, the cities Sofia and London will initially be selected. Any further changes in the combobox's selection will reflect on the selectedCities array.
<igx-combo [data]="cities" [(ngModel)]="selectedCities" displayKey="name" valueKey="id"></igx-combo>
export class MyCombo {
public cities: { name: string, id: string }[] = [
{ name: 'Sofia', id: 'BG01' }, { name: 'London', id: 'UK01' }, ...];
public selectedCities: string[] = ['BG01', 'UK01'];
}
Two-way binding can also be achieved without a specified valueKey. For example, if valueKey is omitted, the bound model will look like this:
export class MyCombo {
public cities: { name: string, id: string } [] = [
{ name: 'Sofia', id: 'BG01' }, { name: 'London', id: 'UK01' }, ...];
public selectedCities: { name: string, id: string } [] = [this.cities[0], this.cities[1]];
}
Selection API
콤보박스 구성 요소는 컨트롤의 현재 선택 상태를 가져오고 조작할 수 있는 API를 노출합니다.
콤보박스의 선택을 얻는 한 가지 방법은 선택 속성을 이용하는 것입니다. 지정된 valueKey (있는 경우)에 따라 선택한 항목에 해당하는 값 배열을 반환합니다.
In our example, selection will return an array of the selected cities' ids:
export class MyCombo {
...
public selection: string[] = this.combo.selection;
}
선택 API를 사용하면 Observable 변경에 대한 응답으로 버튼 클릭을 통해 컨트롤과 사용자 상호 작용 없이 콤보박스의 선택된 항목을 변경할 수도 있습니다. 예를 들어 도시 집합을 선택하는 버튼을 구현할 수 있습니다. select() 메소드를 사용하여:
<igx-combo [data]="cities" displayKey="name" valueKey="id"></igx-combo>
<button igxButton (click)="selectFavorites()">Select Favorites</button>
버튼을 클릭하면 런던과 소피아 도시가 콤보박스 선택 항목에 추가됩니다.
export class MyExampleCombo {
@ViewChild(IgxComboComponent, { read: IgxComboComponent, static: true })
public combo: IgxComboComponent;
...
selectFavorites(): void {
this.combo.select(['UK01', 'BG01']);
}
}
또한 콤보박스는 선택 항목이 변경될 때마다 이벤트(SelectionChanging() )를 발생시킵니다. 내보낸 이벤트 인수인 IComboSelectionChangingEventArgs 에는 변경 전 선택 항목, 현재 선택 항목, 추가되거나 제거된 항목에 대한 정보가 포함되어 있습니다. 이벤트를 취소하여 새 항목 배열로 선택 항목이 업데이트되지 않도록 할 수도 있습니다.
Binding to the event can be done through the proper @Output property on the igx-combo tag:
<igx-combo [data]="cities" displayKey="name" valueKey="id"
(selectionChanging)="handleCityChange($event)">
</igx-combo>
다음 예에서는 도시가 선택 항목에 추가되거나 제거되면 통계 시각화를 업데이트하는 핸들러가 실행됩니다.
export class MyExampleCombo {
...
handleCityChange(event: IComboSelectionChangeEventArgs): void {
for (const item of event.added) {
this.addToVisualization(item);
}
for (const item of event.removed) {
this.removeFromVisualization(item);
}
}
}
Single Selection
By default, the combo control provides multiple selection. The snippet below demonstrates how to achieve single selection in the component by attaching a handler to the selectionChanging event:
<igx-combo [data]="lData" (selectionChanging)="singleSelection($event)"></igx-combo>
public singleSelection(event: IComboSelectionChangeEventArgs) {
if (event.added.length) {
event.newValue = event.added;
}
}
참고: 위에 표시된 것처럼 igxCombo를 수정하는 대신 igxSimpleCombo를 사용하는 것이 좋습니다.
Keyboard Navigation
콤보박스가 닫혀 있고 포커스가 있을 때:
ArrowDownorAlt+ArrowDownwill open the combobox's drop down and will move focus to the search input.
콤보 상자가 열리고 검색 입력에 초점이 맞춰지면:
ArrowUporAlt+ArrowUpwill close the combobox's drop down and will move focus to the closed combobox.ArrowDownwill move focus from the search input to the first list item. If the list is empty and custom values are enabled will move it to the Add new item button.
Note
다른 키 입력은 입력에 의해 처리됩니다.
콤보박스가 열리고 목록 항목에 포커스가 있을 때:
ArrowDownwill move to the next list item. If the active item is the last one in the list and custom values are enabled, the focus will be moved to the Add item button.ArrowUpwill move to the previous list item. If the active item is the first one in the list, the focus will be moved back to the search input.Endwill move to the last list item.Homewill move to the first list item.Spacewill select/deselect the active list item.Enterwill confirm the already selected items and will close the list.Escwill close the list.
콤보 상자가 열리면 사용자 정의 값 허용이 활성화되고 항목 추가 버튼에 초점이 맞춰집니다.
Enterwill add a new item withvalueKeyanddisplayKeyequal to the text in the search input and will select the new item.ArrowUpfocus will be moved back to the last list item or if the list is empty, will be moved to the search input.
스타일링
Combo Theme Property Map
주요 속성을 수정하면 관련된 모든 종속 속성이 자동으로 업데이트됩니다:
| 기본 속성 | 종속 속성 | 설명 |
|---|---|---|
| $empty-목록-배경 | $empty-list-placeholder-color | 조합된 임시 텍스트 색상. |
$toggle-버튼-배경 |
$toggle-버튼-전경 | 콤보 토글 버튼의 전경 색상. |
| $toggle-버튼-배경-초점 | 콤보 토글 버튼은 초점을 맞춰 있을 때 배경색이 나옵니다. | |
| $toggle-버튼-배경-초점--테두리 | 콤보 토글 버튼 배경색은 초점 맞추면 (테두리 변형) | |
| $toggle 버튼 전경 채우기 | 콤보 토글 버튼은 채워질 때 전경 색상을 사용합니다. | |
| $toggle-버튼-배경-비활성화 | 콤보 토글 버튼은 비활성화 시 배경색이 됩니다. | |
| $toggle 버튼-전경-비활성화 | 콤보 토글 버튼은 비활성화 시 전경 색상을 표시합니다. | |
| $toggle-버튼-배경-초점 | $toggle 버튼-전경-초점 | 콤보 토글 버튼은 초점을 맞출 때 전경 색상을 조절합니다. |
| $clear-버튼-배경-초점 | $clear 버튼-전경-초점 | 콤보 버튼은 초점을 맞추면 전경 색상을 클리어합니다. |
Using the Ignite UI for Angular Theming, we can greatly alter the combobox appearance. First, in order for us to use the functions exposed by the theme engine, we need to import the index file in our style file:
@use "igniteui-angular/theming" as *;
// IMPORTANT: Prior to Ignite UI for Angular version 13 use:
// @import '~igniteui-angular/lib/core/styles/themes/index';
Following the simplest approach, we create a new theme that extends the combo-theme. By setting the $toggle-button-background, the theme automatically determines suitable state colors and contrast foregrounds for the button. You can also specify additional parameters, such as $search-separator-border-color:
$custom-combo-theme: combo-theme(
$search-separator-border-color: #1d3743,
$toggle-button-background: #57a5cd,
);
The IgxComboComponent uses the IgxDropDownComponent internally as an item container. It also includes the IgxInputGroup and the IgxCheckbox components. Creating new themes, that extend these components' themes, and scoping them under the respective classes will let you change the combobox styles:
$custom-drop-down-theme: drop-down-theme(
$background-color: #57a5cd,
);
$custom-checkbox-theme: checkbox-theme(
$border-radius: 10px,
$fill-color: #1d3743,
$empty-color: #1d3743,
);
마지막 단계는 구성 요소의 테마를 포함하는 것입니다.
:host ::ng-deep {
@include css-vars($custom-combo-theme);
@include css-vars($custom-drop-down-theme);
@include css-vars($custom-checkbox-theme);
}
Note
The IgxCombo component uses the IgxOverlay service to hold and display the combobox items list container. To properly scope your styles you might have to use an OverlaySetting.outlet. For more details check the IgxOverlay Styling Guide. Also is necessary to use ::ng-deep when we are styling the components.
Note
The default type of the IgxCombo is box unlike the IgxSelect where it is line.
Demo
Styling with Tailwind
저희 맞춤형 Tailwind 유틸리티 클래스를 사용해 스타일combo 링할 수 있습니다. 먼저 Tailwind를 꼭 설정 하세요.
전역 스타일시트의 순풍 가져오기와 함께 다음과 같이 원하는 테마 유틸리티를 적용할 수 있습니다.
@import "tailwindcss";
...
@use 'igniteui-theming/tailwind/utilities/material.css';
유틸리티 파일에는 테마 변형 두 가지light가dark 모두 포함되어 있습니다.
- 라이트 테마에는 클래스를 사용
light-*하세요. - 어두운 테마에는 클래스를 사용
dark-*하세요. - 접두사 뒤에 컴포넌트 이름을 덧붙이세요,
light-combodark-combo예: .
이 클래스들이 적용되면 동적 테마 계산이 가능합니다. 그 다음에는 생성된 CSS 변수를 무arbitrary properties 시할 수 있습니다. 콜론 다음에는 유효한 CSS 색상 형식(HEX, CSS 변수, RGB 등)을 입력하세요.
콤 보 테마에서 전체 부동산 목록을 확인할 수 있습니다. 문법은 다음과 같습니다:
<igx-combo
class="!light-combo
![--toggle-button-background:#99BAA6]
![--clear-button-foreground:#99BAA6]"
...></igx-combo>
Note
느낌표(!)는 유틸리티 클래스가 우선순위가 되도록 보장하기 위해 필요합니다. Tailwind는 레이어에 스타일을 적용하는데, 이 스타일을 중요하게 표시하지 않으면 컴포넌트의 기본 테마에 의해 덮어쓰여집니다.
마지막에 콤보는 이렇게 보여야 합니다:
Known Issues
- 선택한 항목을 표시하는 콤보박스 입력은 편집할 수 없습니다. 그러나 FireFox의 브라우저 특성으로 인해 커서가 표시됩니다.
- When the combobox is bound to an array of primitive data which contains
undefined(i.e.[ undefined, ...]),undefinedis not displayed in the dropdown. When it is bound to an array of complex data (i.e. objects) and the value used forvalueKeyisundefined, the item will be displayed in the dropdown, but cannot be selected. - 콤보 상자가 원격 서비스에 바인딩되어 있고 미리 정의된 선택 항목이 있는 경우 해당 입력은 요청된 데이터가 로드될 때까지 공백으로 유지됩니다.
Note
The combobox uses igxForOf directive internally hence all igxForOf limitations are valid for the combobox. For more details see igxForOf Known Issues section.
API Summary
사용된 관련 API가 포함된 추가 각도 구성요소 및/또는 지시어:
Theming Dependencies
Additional Resources
우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.