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';
// 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';
// 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;
}
Now that you have the Ignite UI for Angular Select module or directives imported, you can start using the igx-select component.
Using the Angular Select
Add the igx-select along with a list of items to choose from. We use igx-select-item to display the items that the igx-select contains.
<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>
By default, the Select component will use the innerText of the item element in the input field. In cases with more complex item templates, you can explicitly set the text property to specify what to display in the input field when this item is selected. For example:
<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>
To see the text property in action with a bit more sophisticated item templates, check the grouping sample below Select with Groups section.
Input Properties
Select 구성 요소는 입력 그룹에 적용할 수 있는 다음 지시문을 지원합니다.
igxLabel- No need to set theforproperty, as linking with the Angular Select input is handled automatically viaaria-labelledby.igx-prefix/igxPrefixigx-suffix/igxSuffix- Note the built-in toggle button suffix will always be displayed last.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
If no placeholder is specified for the Select component and there is no selection made, the igxLabel will transition and appear where you would expect the placeholder to be.
Group Select Items
To help visually separate item groups, the select component supports item grouping by wrapping items in an <igx-select-item-group>.
This works best with hierarchical data that can be iterated to declare the components. In the following example, each group has a label and a collection of 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>
Header & Footer
Currently, there are no default header and footer templates for the Select component. However, you can add a header or a footer template by marking them respectively with igxSelectHeader or igxSelectFooter. As these are custom templates, you should define their styling as well.
In this example, there are both header and footer ng-templates defined. In the header there is a basic filtering, implemented via igx-buttongroup. The footer includes static summary of all of the items, based on the delivery method.
<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
You can customize the default toggle button, using the igxSelectToggleIcon directive or setting a TemplateRef to the toggleIconTemplate property.
<igx-select #select>
...
<ng-template igxSelectToggleIcon let-collapsed>
<igx-icon>{{ collapsed ? 'add_circle' : 'add_circle_outline'}}</igx-icon>
</ng-template>
...
<igx-select>
Keyboard Navigation
- Open the
igx-selectby clicking on theSpace,EnterorALT + Up/Down Arrowkeys, while the select is focused. - Close the
igx-selectusing theALT + Up/Down Arrowcombination or any of theEnter,Space,EscorTabkeys. - Using the
Up/Down Arrowkeys will navigate through the items. - Using the
HomeorEndkeys will navigate you to the first and last items in the list. - 해당 키를 눌러 특정 문자로 시작하는 목록 항목을 탐색할 수 있습니다.
- 이동하려는 항목의 처음 몇 글자를 빠르게 입력하여 특정 항목으로 이동할 수 있습니다.
- Select an item using the
EnterorSpacekeys
Note
igx-select supports only single selection of items.
또한 드래그 앤 드롭 App Builder ™ 사용하여 특정 프로세스를 자동화하고 다음 Angular 앱을 구축할 때 과도한 수동 코딩의 필요성을 줄이는 방법을 확인할 수 있습니다.
Custom Overlay Settings
You can create custom OverlaySettings. To do this you first define your template like so:
<igx-select [overlaySettings]="customOverlaySettings">
<igx-select-item *ngFor="let item of items">
{{item}}
</igx-select-item>
</igx-select>
- Where the
overlaySettingsproperty is bound to your custom settings.
수업 내에는 다음과 같은 내용이 있습니다.
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
If you pass in your custom settings both as an argument in the open function and in the template, igx-select will use the one provided in the open function. However, if you bind the settings to an internal event, such as opening or opened then igx-select will use the settings that are provided in the template.
스타일링
Select Theme Property Map
기본 속성을 수정하면 모든 관련 종속 속성이 자동으로 업데이트되어 변경 내용이 반영됩니다.
| 기본 속성 | 종속 속성 | 설명 |
|---|---|---|
$toggle-버튼-배경 |
$toggle-버튼-전경 | 토글 버튼의 전경 색상 |
| $toggle 버튼 전경 채우기 | 토글 버튼이 채워졌을 때 전경 색상 | |
| $toggle-버튼-배경-초점 | 초점 시 배경색 | |
| $toggle-버튼-배경-초점--border (부트스트랩/인디고) | 보더 변형(부트스트랩/인디고)에 집중할 때의 배경 | |
| $toggle 버튼-전경-초점 | 토글 버튼이 초점을 맞췄을 때 전경 색상 |
모든 구성 요소에는 고유한 테마 기능이 있습니다.
To get the Select component styled, you have to style its containing components. In our case, these are the input-group-theme and the drop-down-theme.
Take a look at the Input Group and the Drop Down styling sections to get a better understanding of how to style those two components.
We also have a select-theme function which is used only for styling the button of our Select component.
To get started with styling the Select component button, we need to import the index file, where all the theme functions and component mixins live:
@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 select-theme and provide only the $toggle-button-background parameter. The theme function will automatically calculate all corresponding background and foreground colors for the different states based on this single value.
$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';
유틸리티 파일에는 테마 변형 두 가지light가dark 모두 포함되어 있습니다.
- 라이트 테마에는 클래스를 사용
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
- IgxSelectComponent
- IgxSelectItemComponent
- IgxDropDown구성요소
- IgxDropDownItemComponent
- 오버레이 설정
- Connected포지셔닝전략
- GlobalPosition전략
- AbsoluteScroll전략
- 위치 설정
Theming Dependencies
Additional Resources
우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.