Angular 드롭 다운 구성 요소 개요
Ignite UI for Angular 미리 정의된 값의 토글 가능한 목록을 표시하고 사용자가 클릭 한 번으로 단일 옵션 항목을 쉽게 선택할 수 있도록 하는 구성 요소입니다. 드롭다운 메뉴로 작동하도록 빠르게 구성하거나 데이터를 그룹화하여 더 유용한 시각적 정보를 제공하는 데 사용할 수 있습니다. 그룹화를 사용하면 플랫 및 계층적 데이터를 모두 사용할 수 있습니다. Drop Down 구성 요소는 선언적 바인딩을 허용하여 추가 콘텐츠와 링크를 포함할 수 있습니다. 이를 통해 Angular 드롭다운 목록 모양의 추가 UI 사용자 지정 및 스타일링을 위한 여지도 남습니다. 이 외에도 키보드 드롭다운 탐색 및 가상화와 같은 주요 기능이 포함되어 있습니다.
Angular Drop Down Example
이 Angular 드롭다운 예제는 드롭다운 목록의 기본 기능을 보여줍니다. 클릭하여 사전 설정 옵션을 확장하고 항목을 선택한 다음 드롭다운을 닫습니다.
Getting Started with Ignite UI for Angular Drop Down
Ignite UI for Angular Drop Down 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.
ng add igniteui-angular
Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.
다음 단계는 다음 단계를 가져오는 것입니다.IgxDropDownModule 당신의 app.module.ts 파일.
// app.module.ts
...
import { IgxDropDownModule } from 'igniteui-angular/drop-down';
// import { IgxDropDownModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxDropDownModule],
...
})
export class AppModule {}
또는16.0.0 독립 실행형 의존성으로 가져오IgxDropDownComponent 거나, 토큰을IGX_DROP_DOWN_DIRECTIVES 사용해 컴포넌트와 그 지원 컴포넌트, 명령어를 가져올 수도 있습니다.
// home.component.ts
import { NgFor } from '@angular/common';
import { IGX_DROP_DOWN_DIRECTIVES } from 'igniteui-angular/drop-down';
import { IgxToggleActionDirective } from 'igniteui-angular/directives';
import { IgxButtonDirective } from 'igniteui-angular/directives';
// import { IGX_DROP_DOWN_DIRECTIVES, IgxToggleActionDirective, IgxButtonDirective } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: `
<button
igxButton="contained"
[igxToggleAction]="dropdown"
[igxDropDownItemNavigation]="dropdown"
>
Options
</button>
<igx-drop-down #dropdown>
<igx-drop-down-item *ngFor="let item of items">
{{ item.field }}
</igx-drop-down-item>
</igx-drop-down>
`,
styleUrls: ['home.component.scss'],
standalone: true,
imports: [ IGX_DROP_DOWN_DIRECTIVES, IgxToggleActionDirective, IgxButtonDirective, NgFor ],
/* or imports: [IgxDropDownComponent, IgxDropDownItemComponent, IgxToggleActionDirective, IgxButtonDirective, NgFor] */
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Drop Down module or directives imported, you can start using the igx-drop-down component.
Using the Angular Drop Down
Add Drop Down
선택할 수 있는 여러 옵션 항목을 제공하는 간단한 드롭다운을 만들어 보겠습니다. 이를 달성하기 위해 IgxDropDownComponent와 IgxToggleAction을 사용하여 드롭다운을 열고 닫습니다.
<!-- dropdown.component.html -->
<button igxButton="contained" [igxToggleAction]="dropdown" [igxDropDownItemNavigation]="dropdown">
Options
</button>
<igx-drop-down #dropdown>
<igx-drop-down-item *ngFor="let item of items">
{{ item.field }}
</igx-drop-down-item>
</igx-drop-down>
// dropdown.component.ts
@Component({...})
export class MyDropDownComponent {
public items: Array<{ field: string }> = [
{ field: 'Option 1' },
{ field: 'Option 2' },
{ field: 'Option 3' }
];
}
More Angular Drop Down Examples
기본 데모는 Angular에서 토글 가능한 드롭다운 목록을 사용하는 방법을 보여줍니다. 이를 통해 최종 사용자는 미리 정의된 모든 항목을 확장하고 그 중 하나를 선택할 수 있습니다. 다음 예제를 확인하고 Angular 드롭다운 목록이 작동하는 모습을 확인하세요.
Predefined selected item
미리 정의된 선택 항목을 갖고 싶다고 가정해 보겠습니다. 이를 수행하는 한 가지 방법은 드롭다운 구성 요소의 열기 이벤트를 처리하는 것입니다.
<!-- dropdown.component.html -->
<button igxButton="contained" [igxToggleAction]="dropdown" [igxDropDownItemNavigation]="dropdown">
Options
</button>
<igx-drop-down #dropdown (opening)="dropdown.setSelectedItem(0)">
<igx-drop-down-item *ngFor="let item of items">
{{ item.field }}
</igx-drop-down-item>
</igx-drop-down>
// dropdown.component.ts
export class MyDropDownComponent {
public items: Array<{ field: string }> = [
{ field: 'Option 1' },
{ field: 'Option 2' },
{ field: 'Option 3' },
];
}
Grouping items
To provide a more useful visual information, use the isHeader property to group items semantically or the disabled property to display an item as a non-interactive. You can also set the selected property on a particular item to make it the selected item. The igx-drop-down items have out-of-the-box support for igxPrefix, igxSuffix, and igx-divider directives that can contain or be set on HTML elements or other web components.
<!-- dropdown.component.html -->
<button igxButton="contained" [igxToggleAction]="dropdown" [igxDropDownItemNavigation]="dropdown">
Countries
</button>
<igx-drop-down #dropdown [width]="'240px'">
<div class="drop-down__scroll-container">
<igx-drop-down-item *ngFor="let item of items" [disabled]="item.disabled" [isHeader]="item.header" [selected]="item.selected">
<igx-icon igxPrefix>place</igx-icon>
{{ item.field }}
<span igxSuffix>{{ item.code }}</span>
<igx-divider></igx-divider>
</igx-drop-down-item>
</div>
</igx-drop-down>
// dropdown.component.ts
export class MyDropDownComponent {
public items: any[] = [
{ field: 'European Union', code: 'EU', header: true },
{ field: 'Germany', code: 'DE' },
{ field: 'Bulgaria', code: 'BG', selected: true },
{ field: 'France', code: 'FR', disabled: true },
{ field: 'North America', code: 'NA', header: true },
{ field: 'Canada', code: 'CA' },
{ field: 'United States', code: 'US' },
{ field: 'Mexico', code: 'MX' },
];
}
샘플이 올바르게 구성되면 국가 목록이 유럽 연합 헤더 아래에 그룹으로 표시되고, 프랑스는 비대화형 항목으로, 불가리아는 선택된 항목으로 표시되어야 합니다.
Grouping hierarchical data
The igx-drop-down items can also be grouped using the igx-drop-down-item-group container, making it easier for users to differentiate separate categories. The igx-drop-down-item-group accepts igx-drop-down-item elements as its content and renders them in a grouped fashion.
// dropdown.component.ts
export class MyCustomDropDownComponent {
...
public foods: {
name: string,
entries: { name: string, refNo: string }[]
}[] = [
{
name: 'Vegetables',
entries: [{
name: 'Cucumber',
refNo: '00000'
}, {
name: 'Lettuce',
refNo: '00001'
},
...]
}, {
name: 'Fruits',
entries: [{
name: 'Banana',
refNo: '10000'
}, {
name: 'Tomato',
refNo: '10001'
},
...]
}, {
name: 'Meats',
entries: [{
name: 'Chicken',
refNo: '20000'
}, {
name: 'Beef',
refNo: '20001'
},
...]
}];
}
<igx-drop-down>
<igx-drop-down-item-group *ngFor="let foodGroup of foods" [label]="foodGroup.name">
<igx-drop-down-item *ngFor="let food of foodGroup.entries" [value]="food.refNo">
{{ food.name }}
</igx-drop-down-item>
</igx-drop-down-item-group>
</igx-drop-down>
The group also has the additional functionality of disabling items inside of its body. For example, lets say we do not want the Meats food group to be selectable in our drop-down. Instead of disabling all of the entries in Meats separately, we can disable the group, as well as all of the child items inside:
<igx-drop-down>
<igx-drop-down-item-group *ngFor="let foodGroup of foods" [label]="foodGroup.name" [disabled]="foodGroup.name === 'Meats'">
<igx-drop-down-item *ngFor="let food of foodGroup.entries" [value]="food.refNo">
{{ food.name }}
</igx-drop-down-item>
</igx-drop-down-item-group>
</igx-drop-down>
아래 샘플에서 결과를 볼 수 있습니다.
Drop Down as menu
드롭다운이 메뉴처럼 작동하도록 구성할 수 있습니다. 이렇게 하려면 ISelectionEventArgs 상호 작용 취소 회원 진실에서 선택변경 이벤트 핸들러. 이런 방식으로 메뉴를 열 때 선택한 항목은 유지되지 않으며 이전 선택 항목은 무효화됩니다. 그래도 클릭한 항목은 다음을 통해 얻을 수 있습니다. 새로운 선택 이벤트 회원가치입니다.
<!-- dropdown.component.html -->
<div>
<igx-navbar title="Contacts">
<button
[igxToggleAction]="menu"
[igxToggleOutlet]="outlet"
[overlaySettings]="overlaySettings"
[igxDropDownItemNavigation]="menu"
igxIconButton="flat"
>
<igx-icon fontSet="material">more_vert</igx-icon>
</button>
<igx-drop-down #menu (selectionChanging)="selectionHandler($event)">
<igx-drop-down-item *ngFor="let item of items" [value]="item.text">
<div>{{ item.text }}</div>
</igx-drop-down-item>
</igx-drop-down>
</igx-navbar>
<div>
<ng-container *ngIf="text">
<label igxLabel>{{ text }}</label>
</ng-container>
</div>
<div igxOverlayOutlet #outlet="overlay-outlet"></div>
</div>
// dropdown.component.ts
export class MyMenuComponent {
public items: Array<{ text: string }> = [
{ text: "Add New Contact" },
{ text: "Edit Contact" },
{ text: "Refresh" },
{ text: "Help" },
];
public text: string;
public overlaySettings = {
positionStrategy: new ConnectedPositioningStrategy({
horizontalDirection: HorizontalAlignment.Left,
horizontalStartPoint: HorizontalAlignment.Right,
verticalStartPoint: VerticalAlignment.Bottom,
}),
scrollStrategy: new NoOpScrollStrategy(),
};
public selectionHandler(eventArgs: ISelectionEventArgs) {
this.text = eventArgs.newSelection.value;
eventArgs.cancel = true;
}
}
Multi-Level Drop Down menu
다음 샘플은 사용자가 일련의 중첩 메뉴 위로 마우스를 가져가면 콘텐츠 계층 구조를 빠르고 쉽게 탐색할 수 있는 다중 레벨 드롭다운 메뉴를 구현하는 방법을 보여줍니다.
For the implementation of the multi-level drop down menu we will use the IgxDropDownComponent as well as a custom directive and service described below.
In order to configure the IgxDropDownItem to open an additional drop down, add the multiLevel directive that would handle the overlay settings of the nested drop down and manages its opened/closed state through its innerDropdown property.
<igx-drop-down #dropdown1>
<igx-drop-down-item [value]="'Web'" multiLevel [innerDropdown]="web">
Web <igx-icon igxSuffix>chevron_right</igx-icon>
</igx-drop-down-item>
...
</igx-drop-down>
<igx-drop-down #web>
<igx-drop-down-item [value]="'App Builder'"> App Builder </igx-drop-down-item>
...
</igx-drop-down>
To configure the multi-level drop down to behave as a menu, you need to handle the selectionChanging event of all drop downs in the hierarchy and cancel the default behavior. Then, in order to handle the selection properly you could use the MultiLevelService's handleSelection method and in order to prevent closing the drop down when clicking on a menu item, use the MultiLevelService's handleClosing methods.
@ViewChildren(IgxDropDownComponent, { read: IgxDropDownComponent })
private _dropdowns: QueryList<IgxDropDownComponent>;
@ViewChild('dropdown1', { read: IgxDropDownComponent })
private _multiLevelDropdown: IgxDropDownComponent;
constructor(private _multiLevelService: MultiLevelService) { }
public ngAfterViewInit(): void {
this._dropdowns.forEach((dropdown) => {
dropdown.selectionChanging.subscribe((args) => {
args.cancel = true;
const value = args.newSelection.value;
const categories = this._multiLevelService.categories;
if (categories.includes(value)) {
this.selection = '';
return;
}
if (this._multiLevelService.isMultiLevel(dropdown)) {
this._multiLevelService.handleSelection();
} else {
dropdown.close();
}
this.selection = value;
});
});
this._multiLevelDropdown.closing.subscribe((args) => {
this._multiLevelService.handleClosing(args);
});
}
위 구성의 결과는 아래 샘플에서 볼 수 있습니다.
Note
처음에 열린 Dropdown 구성 요소를 표시하려면 open 메서드를 requestAnimationFrame 메서드의 콜백으로 설정하는 것이 좋습니다. 이렇게 하면 DOM 트리가 다시 그려지고 모든 요소가 올바르게 배치됩니다.
Navigation directive
Use the igxDropDownItemNavigation directive to enable keyboard navigation for the igxDropDown component. In order to allow the directive to handle all triggered events, it should be applied to the active (focused) element or a parent container. By default, a drop-down or its items don't take focus, so the directive can be placed on a button or input that will control the drop-down. The navigation directive value should target a component that is an instance or a descendant of the IgxDropDownBaseDirective class.
The following sample demonstrates an input that opens and closes the igxDropDown instance on click. Applying the igxDropDownItemNavigation directive on the input itself will enable keyboard navigation when using the up and down arrow keys. This relies on the default drop-down behavior with the allowItemsFocus property set to false to allow the input to maintain focus.
<!-- input-dropdown.component.html -->
<igx-input-group #inputGroup [igxToggleAction]="dropDown">
<input
type="text"
igxInput
[igxDropDownItemNavigation]="dropDown"
readonly="true"
placeholder="choose an option"
[value]="dropDown.selectedItem?.value"
(keydown.ArrowDown)="openDropDown()"
/>
<igx-suffix igxIconButton="flat" igxRipple>
<igx-icon>arrow_drop{{ dropDown.collapsed ? '_down' : '_up' }}</igx-icon>
</igx-suffix>
</igx-input-group>
<span>Selected: {{ dropDown.selectedItem?.value }}</span>
<igx-drop-down #dropDown [width]="'160px'">
<igx-drop-down-item *ngFor="let item of items" [value]="item.field">
{{ item.field }}
</igx-drop-down-item>
</igx-drop-down>
// input-dropdown.component.ts
export class InputDropDownComponent {
@ViewChild(IgxDropDownComponent) public igxDropDown: IgxDropDownComponent;
@ViewChild('inputGroup', { read: IgxInputGroupComponent })
public inputGroup: IgxInputGroupComponent;
public items: Array<{ field: string }> = [
{ field: 'Option 1' },
{ field: 'Option 2' },
{ field: 'Option 3' },
];
public openDropDown() {
if (this.igxDropDown.collapsed) {
this.igxDropDown.open({
modal: false,
positionStrategy: new ConnectedPositioningStrategy({
target: this.inputGroup.element.nativeElement,
}),
});
}
}
}
지시문을 적용하면 키보드 탐색의 결과로 다음 작업이 실행됩니다.
| 이름 | 설명 |
|---|---|
Enter |
드롭다운에서 항목을 선택하고 드롭다운을 닫습니다. |
Space |
드롭다운에서 항목을 선택하고 드롭다운을 닫습니다. |
Esc |
드롭다운을 닫습니다. |
Arrow Down |
대상 구성 요소의 다음 항목으로 이동합니다. |
Arrow Up |
대상 구성요소의 이전 항목으로 이동합니다. |
End |
대상 구성 요소의 마지막 항목으로 이동합니다. |
Home |
대상 구성 요소의 첫 번째 항목으로 이동합니다. |
When the allowItemsFocus property is enabled, the drop down items gain tab index and are focused when active. The focused drop-down items are the ones that trigger events, during keyboard navigation, which means that the navigation directive should be applied on the individual drop-down items.
<igx-input-group [igxToggleAction]="dropDown">
<input igxInput type="text" />
</igx-input-group>
<igx-drop-down #dropDown [allowItemsFocus]="true">
<igx-drop-down-item *ngFor="let p of provinceData" [igxDropDownItemNavigation]="dropDown">
{{ p }}
</igx-drop-down-item>
</igx-drop-down>
스타일링
Dropdown Theme Property Map
주요 속성을 수정하면 관련된 모든 종속 속성이 자동으로 업데이트됩니다:
| 기본 속성 | 종속 속성 | 설명 |
|---|---|---|
$background색 |
$item-텍스트-컬러 | 드롭다운 항목 텍스트 색상. |
| $hover-항목-배경 | 드롭다운 호버 아이템 배경색. | |
| $focused-항목-배경 | 드롭다운 아이템 배경색에 초점을 맞추는 것. | |
| $focused-항목-텍스트-색상 | 드롭다운 초점에 맞는 항목 텍스트 색상. | |
| $selected-항목-배경 | 드롭다운에서 선택한 항목 배경색. | |
| $disabled-항목-텍스트-색상 | 드롭다운 메뉴는 아이템 텍스트 색상을 비활성화합니다. | |
| $header-텍스트-컬러 | 드롭다운 헤더 텍스트 색상. | |
$item-텍스트-컬러 |
$item-아이콘-컬러 | 드롭다운 아이템 아이콘 색상. |
| $hover-항목-텍스트-색상 | 드롭다운 항목 마우스 텍스트 색상. | |
| $hover-아이템-아이콘-색상 | 드롭다운 아이템 호버 아이콘 색상. | |
$selected-항목-배경 |
$selected-항목-텍스트-색상 | 드롭다운 메뉴에서 항목 텍스트 색상을 선택하세요. |
| $selected-아이템-아이콘-색상 | 드롭다운 메뉴에서 아이템 아이콘 색상을 선택하세요. | |
| $selected-호버-아이템-배경 | 선택한 드롭다운 아이템은 배경색을 떠올립니다. | |
| $selected-호버-항목-텍스트-컬러 | 드롭다운 메뉴 선택 버튼은 텍스트 색상을 마우스로 고정합니다. | |
| $selected-아이템 아이콘-색상 호버 | 드롭다운 메뉴에서 아이템 선택, 호버 아이콘 색상. | |
| $selected-초점-항목-배경 | 선택한 항목은 배경색에 초점을 맞추는 드롭다운 메뉴입니다. | |
| $selected-focus-item-text-color | 드롭다운 메뉴 선택 시 텍스트 색상에 초점을 맞추세요. | |
| $focused-항목-테두리-색상 | 드롭다운 아이템 중심 테두리 색상. |
Using the Ignite UI for Angular Theming, we can greatly alter the drop-down 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 drop-down-theme and accepts some of the default theme's parameters. When you provide a certain background color, the theme automatically calculates the state colors and appropriate contrasting foregrounds. By setting the $background property, you'll get a fully styled dropdown.
$custom-drop-down-theme: drop-down-theme(
$header-text-color: #345779,
$item-text-color: #2dabe8,
$hover-item-text-color: #345779,
$selected-item-background: #345779,
);
마지막 단계는 사용자 정의 드롭다운 테마를 클래스 또는 요소 선택기에 전달하는 것입니다.
.drop-down__scroll-container {
@include css-vars($custom-drop-down-theme);
}
Demo
API Summary
- IgxDropDown구성요소
- IgxDropDown컴포넌트 스타일
- IgxDropDownItemComponent.
- Igx오버레이
- Igx오버레이 스타일
- IgxDivider 지시문
- IgxDivider 지시어 스타일
Theming Dependencies
Additional Resources
우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.