Angular Single Select ComboBox 구성 요소 개요
Angular Single Select ComboBox 구성 요소는 단일 선택을 허용하는 ComboBox 구성 요소 의 수정판입니다. 우리는 이것을 "단순 콤보"라고 부릅니다. 원래 ComboBox 구성 요소에 대한 단일 선택 모드에 대한 수요가 높아서, 사용자가 미리 정의된 항목 목록에서 옵션을 선택하고 사용자 지정 값을 입력할 수 있는 편집 가능한 검색 입력을 제공하는 확장 구성 요소를 만들었습니다.
Angular Simple ComboBox 예제
이 Angular Simple ComboBox 예제에서는 사용자가 차트의 추세선 유형을 선택하는 방법을 볼 수 있습니다. 또한 Simple ComboBox는 키보드 탐색 및 사용자 지정 스타일 기능을 제공합니다.
import { Component, OnInit } from '@angular/core' ;
import { IgRect } from 'igniteui-angular-core' ;
import { StockData, updatedStockData } from '../../../data/stocks-data' ;
import { IgxSimpleComboComponent, IgxButtonGroupComponent, IgxButtonDirective } from 'igniteui-angular' ;
import { FormsModule } from '@angular/forms' ;
import { NgFor } from '@angular/common' ;
import { IgxFinancialChartCoreModule } from 'igniteui-angular-charts' ;
@Component ({
selector : 'app-simple-combo-main' ,
templateUrl : 'simple-combo-main.component.html' ,
styleUrls : ['simple-combo-main.component.scss' ],
imports : [IgxSimpleComboComponent, FormsModule, IgxButtonGroupComponent, NgFor, IgxButtonDirective, IgxFinancialChartCoreModule]
})
export class SimpleComboMainComponent implements OnInit {
public data: StockData[] = updatedStockData;
public selectedRange: string ;
public trendLineType: string ;
public trendLineTypes: string [] = [
'CubicFit' ,
'LinearFit' ,
'QuinticFit' ,
'QuarticFit' ,
'ExponentialFit' ,
'PowerLawFit' ,
'LogarithmicFit' ,
'CumulativeAverage' ,
'ExponentialAverage' ,
'SimpleAverage' ,
'ModifiedAverage' ,
'WeightedAverage' ,
'None'
];
public windowRect: IgRect = { top : 0 , left : 0 , width : 1 , height : 1 };
public ranges: string [] = ['1M' , '3M' , '6M' , 'YTD' , '1Y' , 'ALL' ];
public rangeButtonClick (range: string ) {
this .selectedRange = range;
let startDate = new Date (Date .now());
switch (range) {
case '1M' :
startDate.setMonth(startDate.getMonth() - 1 );
break ;
case '3M' :
startDate.setMonth(startDate.getMonth() - 3 );
break ;
case '6M' :
startDate.setMonth(startDate.getMonth() - 6 );
break ;
case 'YTD' :
startDate = new Date (startDate.getFullYear(), 0 , 1 );
break ;
case '1Y' :
startDate.setFullYear(startDate.getFullYear() - 1 );
break ;
case 'ALL' :
startDate = this .data[0 ].time;
break ;
}
this .windowRect = this .getWindowRect(startDate);
}
public ngOnInit(): void {
this .selectedRange = this .ranges[0 ];
this .trendLineType = this .trendLineTypes[0 ];
this .rangeButtonClick(this .selectedRange);
}
private getWindowRect(startDate: Date ): IgRect {
const startDateIndex = this .data.findIndex(d => d.time > startDate);
return {
top : 0 ,
left : startDateIndex / this .data.length,
width : 1 - startDateIndex / this .data.length,
height : 1
};
}
}
ts コピー <div class ="sample-wrapper" >
<div class ="combo-section" >
<igx-simple-combo class ="input-container"
[data ]="trendLineTypes"
[(ngModel )]="trendLineType"
[type ]="'border'"
> </igx-simple-combo >
<igx-buttongroup >
<button igxButton
[selected ]="range === selectedRange"
(buttonClick )="rangeButtonClick(range)"
*ngFor ="let range of ranges"
> {{range}}</button >
</igx-buttongroup >
</div >
<igx-financial-chart
width ="100%"
height ="100%"
[dataSource ]="data"
trendLineBrushes ="rgba(0, 101, 209, 1)"
zoomSliderType ="None"
[isToolbarVisible ]="false"
[trendLineType ]="trendLineType"
[windowRect ]="windowRect"
> </igx-financial-chart >
</div >
html コピー .sample-wrapper {
padding : 1rem 1rem 6rem 1rem ;
width : 100% ;
height : 100% ;
}
.combo-section {
display : flex;
justify-content : space-between;
margin-bottom : 3rem ;
}
.input-container {
flex-grow : 1 ;
max-width : 300px ;
}
scss コピー
이 샘플이 마음에 드시나요? 전체 Ignite UI for Angular 툴킷에 액세스하고 몇 분 안에 나만의 앱을 구축해 보세요. 무료로 다운로드하세요.
Angular Simple ComboBox 기능
간단한 콤보박스 컨트롤은 다음 기능을 제공합니다. - 데이터 바인딩 - 로컬 데이터 및 원격 데이터 - 값 바인딩 - 필터링 - 그룹화 - 사용자 정의 값 - 템플릿 - 템플릿 기반 양식 및 반응형 양식과의 통합
Ignite UI for Angular Simple ComboBox 시작하기
Ignite UI for Angular Simple ComboBox 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.
ng add igniteui-angular
cmd
Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.
다음 단계는 IgxSimpleComboModule
당신의 app.module.ts 파일.
import { IgxSimpleComboModule } from 'igniteui-angular' ;
@NgModule ({
imports : [
...
IgxSimpleComboModule,
...
]
})
export class AppModule {}
typescript
또는 16.0.0
부터 IgxSimpleComboComponent
독립 실행형 종속성으로 가져오거나 IGX_SIMPLE_COMBO_DIRECTIVES
토큰을 사용하여 구성 요소와 모든 지원 구성 요소 및 지시어를 가져올 수 있습니다.
import { IGX_SIMPLE_COMBO_DIRECTIVES } from 'igniteui-angular' ;
@Component ({
selector : 'app-home' ,
template : '<igx-simple-combo></igx-simple-combo>' ,
styleUrls : ['home.component.scss' ],
standalone : true ,
imports : [IGX_SIMPLE_COMBO_DIRECTIVES]
})
export class HomeComponent {}
typescript
이제 Ignite UI for Angular 가져왔으므로 igx-simple-combo
구성 요소를 사용할 수 있습니다.
Angular Simple ComboBox 사용
일반 콤보박스와 마찬가지로 igx-simple-combo를 데이터에 바인딩할 수 있습니다.
export class MySimpleComboComponent implements OnInit {
public cities: City[];
public ngOnInit ( ) {
this .cities = getCitiesByPopulation(10000000 );
}
}
typescript
<igx-simple-combo [data ]="cities" > </igx-simple-combo >
html
이제 간단한 콤보박스가 도시 배열에 바인딩되었습니다.
데이터 값 및 표시 속성
간단한 콤보박스는 복잡한 데이터(예: 개체)의 배열에 바인딩되어 있으므로 컨트롤이 선택한 항목을 처리하는 데 사용할 속성을 지정해야 합니다. 컨트롤은 두 개의 @Input
속성(valueKey 및 displayKey) 을 노출합니다.
valueKey
-선택 사항, 개체 배열에 권장됨 - 단순 콤보 상자 선택을 위해 저장될 데이터 항목의 속성을 지정합니다. valueKey
생략하면 단순 콤보박스 값은 데이터 항목에 대한 참조를 사용합니다(즉, 선택 항목은 igxSimpleCombo.data
의 항목 배열이 됩니다).
displayKey
-객체 배열에 필수 - 항목의 텍스트에 사용될 속성을 지정합니다. displayKey
에 값이 지정되지 않으면 단순 콤보박스는 지정된 valueKey
(있는 경우)를 사용합니다.
우리의 경우에는 각 도시의 name
과 각 도시의 id
저장하는 값을 표시하는 간단한 콤보박스를 원합니다. 따라서 이러한 속성을 각각 간단한 콤보 상자의 displayKey
및 valueKey
값으로 바인딩합니다.
<igx-simple-combo [data ]="cities" [displayKey ]="'name'" [valueKey ]="'id'" > </igx-simple-combo >
html
데이터 소스가 단순 유형으로 구성된 경우(예: string[]
, number[]
), 하지 마라 지정하다 valueKey
그리고 displayKey
.
양방향 바인딩
간단한 콤보박스 구성 요소는 [(ngModel)]
사용한 양방향 데이터 바인딩은 물론 템플릿 기반 및 반응 형 형식에서의 사용도 완벽하게 지원합니다. 간단한 콤보박스 선택은 양방향 바인딩이나 선택 API를 통해 액세스할 수 있습니다. 간단한 콤보 상자 선택 항목과 동일한 유형의 항목(valueKey
기준)을 전달할 수 있으며, 하나가 변경될 때마다 다른 항목도 그에 따라 업데이트됩니다.
다음 예에서는 제공된 데이터의 첫 번째 도시가 처음에 선택됩니다. 단순 콤보박스 선택의 추가 변경사항은 selectedCities
에 반영됩니다.
<igx-simple-combo [data ]="cities" [(ngModel )]="selectedCity" [displayKey ]="'name'" [valueKey ]="'id'" > </igx-simple-combo >
html
export class MySimpleComboComponent implements OnInit {
public cities: City[];
public selectedCity: number ;
public ngOnInit(): void {
this .cities = getCitiesByPopulation(10000000 );
this .selectedCity = this .cities[0 ].id;
}
}
typescript
import { Component, OnInit } from '@angular/core' ;
import { City, getCitiesByPopulation } from '../../../data/cities15000-regions-countries' ;
import { IgxSimpleComboComponent } from 'igniteui-angular' ;
import { FormsModule } from '@angular/forms' ;
import { NgIf } from '@angular/common' ;
@Component ({
selector : 'app-simple-combo-usage' ,
templateUrl : 'simple-combo-usage.component.html' ,
styleUrls : ['simple-combo-usage.component.scss' ],
imports : [IgxSimpleComboComponent, FormsModule, NgIf]
})
export class SimpleComboUsageComponent implements OnInit {
public cities: City[];
public selectedCity: number ;
public ngOnInit(): void {
this .cities = getCitiesByPopulation(10000000 );
this .selectedCity = this .cities[0 ].id;
}
}
ts コピー <div class ="sample-wrapper" >
<div class ="combo-section" >
<igx-simple-combo [data ]="cities" [displayKey ]="'name'" [valueKey ]="'id'" [(ngModel )]="selectedCity" >
</igx-simple-combo >
</div >
<div *ngIf ="!!selectedCity" >
<h6 > Selected City's Id:</h6 >
<div > {{ selectedCity }}</div >
</div >
</div >
html コピー .sample-wrapper {
width : 430px ;
margin : 16px ;
}
.combo-section {
width : 100% ;
margin-bottom : 16px ;
}
scss コピー
지정된 valueKey
없이 양방향 바인딩을 구현할 수도 있습니다. 예를 들어 valueKey
생략되면 바인딩된 모델은 다음과 같습니다.
export class MySimpleComboComponent {
public cities: City[] = [
{ name : 'Sofia' , id : '1' }, { name : 'London' , id : '2' }, ...];
public selectedCity: City = this .cities[0 ];
}
typescript
선택 API
간단한 콤보박스 구성 요소는 컨트롤의 현재 선택 상태를 가져오고 조작할 수 있는 API를 노출합니다.
선택을 얻는 한 가지 방법은 선택 속성을 이용하는 것입니다. 지정된 valueKey (있는 경우)에 따라 선택한 항목에 해당하는 값을 반환합니다.
이 예에서는 selection
선택한 도시의 id
반환합니다.
export class MySimpleComboComponent {
...
public selection: string = this .simpleCombo.selection;
}
typescript
선택 API를 사용하면 Observable 변경에 대한 응답으로 버튼 클릭을 통해 컨트롤과 사용자 상호 작용 없이 간단한 콤보 상자의 선택된 항목을 변경할 수도 있습니다. 예를 들어 다음을 사용하여 도시를 선택하는 버튼을 구현할 수 있습니다. 선택 방법:
<igx-simple-combo [data ]="cities" [displayKey ]="'name'" [valueKey ]="'id'" > </igx-simple-combo >
<button igxButton (click )="selectFavorite()" > Select Favorite</button >
html
버튼을 클릭하면 London
단순 콤보박스의 선택 항목에 추가됩니다.
export class MySimpleComboComponent {
@ViewChild (IgxSimpleComboComponent, { read : IgxSimpleComboComponent, static : true })
public simpleCombo: IgxSimpleComboComponent;
...
selectFavorites(): void {
this .simpleCombo.select('2' );
}
}
typescript
또한 간단한 콤보박스는 선택 항목이 변경될 때마다 이벤트(SelectionChanging ) 를 발생시킵니다. 내보낸 이벤트 인수인 ISimpleComboSelectionChangingEventArgs 에는 변경 전 선택 사항, 현재 선택 사항 및 표시된 항목에 대한 정보가 포함되어 있습니다. 이벤트가 취소되어 선택이 이루어지지 않을 수도 있습니다.
igx-simple-combo
태그의 적절한 @Output
속성을 통해 이벤트에 바인딩할 수 있습니다.
<igx-simple-combo [data ]="cities" [displayKey ]="'name'" [valueKey ]="'id'"
(selectionChanging )="handleCityChange($event)" >
</igx-simple-combo >
html
키보드 탐색
단순 콤보박스가 닫히고 포커스가 맞춰진 경우:
ArrowDown
또는 Alt
+ ArrowDown
간단한 콤보 상자의 드롭다운을 엽니다.
간단한 콤보 상자가 열리고 목록의 항목에 초점이 맞춰지면:
ArrowDown
다음 목록 항목으로 이동합니다. 활성 항목이 목록의 마지막 항목이고 사용자 정의 값이 활성화된 경우 포커스가 항목 추가 버튼으로 이동됩니다.
ArrowUp
이전 목록 항목으로 이동합니다. 활성 항목이 목록의 첫 번째 항목인 경우 초점은 검색 입력으로 다시 이동하는 동시에 입력의 모든 텍스트도 선택됩니다.
End
마지막 목록 항목으로 이동합니다.
Home
첫 번째 목록 항목으로 이동합니다.
Space
활성 목록 항목을 선택/선택 취소합니다.
Enter
활성 목록 항목을 선택/선택 취소하고 목록을 닫습니다.
Esc
누르면 목록이 닫힙니다.
단순 콤보 상자가 열리고 사용자 정의 값 허용이 활성화되고 항목 추가 버튼에 초점이 맞춰진 경우:
계단식 시나리오
다음 샘플은 igx-simple-combo가 사용되는 시나리오를 보여줍니다.
import { Component, OnInit } from '@angular/core' ;
import { ISimpleComboSelectionChangingEventArgs, IgxSimpleComboComponent, IgxLinearProgressBarComponent } from 'igniteui-angular' ;
import { City, Country, getCitiesByCountry, getCountries, Region } from '../../../data/cities15000-regions-countries' ;
import { FormsModule } from '@angular/forms' ;
import { NgIf } from '@angular/common' ;
@Component ({
selector : 'app-simple-combo-cascading' ,
templateUrl : 'simple-combo-cascading.component.html' ,
styleUrls : ['simple-combo-cascading.component.scss' ],
imports : [IgxSimpleComboComponent, FormsModule, NgIf, IgxLinearProgressBarComponent]
})
export class SimpleComboCascadingComponent implements OnInit {
public selectedCountry: Country;
public selectedRegion: Region;
public selectedCity: City;
public countriesData: Country[];
public regionData: Region[] = [];
public citiesData: City[] = [];
public isLoadingRegions: boolean = false ;
public isLoadingCities: boolean = false ;
private loadingTime = 0 ;
public ngOnInit(): void {
this .countriesData = getCountries(['United States' , 'Japan' , 'United Kingdom' ]);
}
public countryChanging (e: ISimpleComboSelectionChangingEventArgs ) {
this .selectedCountry = e.newValue as Country;
if (e.newValue){
this .regionData = [];
this .isLoadingRegions = true ;
this .loadingTime = 2000 ;
} else {
this .selectedRegion = undefined ;
this .selectedCity = undefined ;
}
setTimeout (() => {
this .regionData = getCitiesByCountry([this .selectedCountry?.name])
.map(c => ({name : c.region, country : c.country}))
.filter((v, i, a ) => a.findIndex(r => r.name === v.name) === i);
this .isLoadingRegions = false ;
}, this .loadingTime)
this .citiesData = [];
this .loadingTime = 0 ;
}
public regionChanging (e: ISimpleComboSelectionChangingEventArgs ) {
this .selectedRegion = e.newValue as Region;
if (e.newValue){
this .citiesData = [];
this .isLoadingCities = true ;
this .loadingTime = 2000 ;
} else {
this .selectedCity = undefined ;
}
setTimeout (() => {
this .citiesData = getCitiesByCountry([this .selectedCountry?.name])
.filter(c => c.region === this .selectedRegion?.name);
this .isLoadingCities = false ;
}, this .loadingTime)
this .loadingTime = 0 ;
}
}
ts コピー <div class ="sample-wrapper" >
<div class ="combo-section" >
<igx-simple-combo #country
[data ]="countriesData"
(selectionChanging )="countryChanging($event)"
placeholder ="Choose Country..."
[(ngModel )]="selectedCountry"
[displayKey ]="'name'" >
</igx-simple-combo >
</div >
<div class ="combo-section" >
<igx-simple-combo #region
[data ]="regionData"
(selectionChanging )="regionChanging($event)"
placeholder ="Choose Region..."
[(ngModel )]="selectedRegion"
[displayKey ]="'name'"
[disabled ]="regionData.length === 0" >
</igx-simple-combo >
<igx-linear-bar
*ngIf ="isLoadingRegions"
type ="info"
[indeterminate ]="true" >
</igx-linear-bar >
</div >
<div class ="combo-section" >
<igx-simple-combo #city
[data ]="citiesData"
placeholder ="Choose City..."
[(ngModel )]="selectedCity"
[displayKey ]="'name'"
[disabled ]="citiesData.length === 0" >
</igx-simple-combo >
<igx-linear-bar
*ngIf ="isLoadingCities"
type ="info"
[indeterminate ]="true" >
</igx-linear-bar >
</div >
</div >
html コピー .sample-wrapper {
width : 430px ;
margin : 16px ;
}
.combo-section {
margin : 20px 10px ;
}
scss コピー
Cascading Combos 샘플을 Angular 보세요.
템플릿 구성
간단한 콤보박스의 API는 한 구성 요소에서 선택한 항목을 가져오고 다음 구성 요소의 데이터 소스를 로드할 뿐만 아니라 필요할 때 선택 항목과 데이터 소스를 지우는 데 사용됩니다.
<igx-simple-combo #country
[data ]="countriesData"
(selectionChanging )="countryChanging($event)"
placeholder ="Choose Country..."
[(ngModel )]="selectedCountry"
[displayKey ]="'name'" >
</igx-simple-combo >
<igx-simple-combo #region
[data ]="regionData"
(selectionChanging )="regionChanging($event)"
placeholder ="Choose Region..."
[(ngModel )]="selectedRegion"
[displayKey ]="'name'"
[disabled ]="regionData.length === 0" >
</igx-simple-combo >
<igx-simple-combo #city
[data ]="citiesData"
placeholder ="Choose City..."
[(ngModel )]="selectedCity"
[displayKey ]="'name'"
[disabled ]="citiesData.length === 0" >
</igx-simple-combo >
html
구성 요소 정의
export class SimpleComboCascadingComponent implements OnInit {
public selectedCountry: Country;
public selectedRegion: Region;
public selectedCity: City;
public countriesData: Country[];
public regionData: Region[] = [];
public citiesData: City[] = [];
public ngOnInit(): void {
this .countriesData = getCountries(['United States' , 'Japan' , 'United Kingdom' ]);
}
public countryChanging (e: ISimpleComboSelectionChangingEventArgs ) {
this .selectedCountry = e.newSelection as Country;
this .regionData = getCitiesByCountry([this .selectedCountry?.name])
.map(c => ({name : c.region, country : c.country}))
.filter((v, i, a ) => a.findIndex(r => r.name === v.name) === i);
this .selectedRegion = null ;
this .selectedCity = null ;
this .citiesData = [];
}
public regionChanging (e: ISimpleComboSelectionChangingEventArgs ) {
this .selectedRegion = e.newSelection as Region;
this .citiesData = getCitiesByCountry([this .selectedCountry?.name])
.filter(c => c.region === this .selectedRegion?.name);
this .selectedCity = null ;
}
}
typescript
Angular Simple ComboBox 원격 바인딩
Ignite UI for Angular 콤보박스를 원격 서비스에 바인딩하고 필요에 따라 데이터를 검색할 수 있는 API를 제공합니다.
데모
아래 샘플은 dataPreLoad 속성을 사용하여 원격 데이터의 새 청크를 로드하고 ComboBox 원격 바인딩 에 설명된 단계를 따르는 원격 바인딩을 보여줍니다.
import { AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core' ;
import { IComboSearchInputEventArgs, IForOfState, IgxSimpleComboComponent, IgxToastComponent, ISimpleComboSelectionChangingEventArgs, VerticalAlignment } from 'igniteui-angular' ;
import { RemoteNWindService } from '../../../services/remoteNwind.service' ;
import { AsyncPipe } from '@angular/common' ;
@Component ({
providers : [RemoteNWindService],
selector : 'app-simple-combo-remote' ,
templateUrl : './simple-combo-remote.component.html' ,
styleUrls : ['./simple-combo-remote.component.scss' ],
imports : [IgxSimpleComboComponent, IgxToastComponent, AsyncPipe]
})
export class SimpleComboRemoteComponent implements OnInit , AfterViewInit {
@ViewChild ('loadingToast' )
public loadingToast: IgxToastComponent;
@ViewChild ('remoteSimpleCombo' , { read : IgxSimpleComboComponent, static : true })
public remoteSimpleCombo: IgxSimpleComboComponent;
public prevRequest: any ;
public rData: any ;
private searchText: string = null ;
private defaultVirtState: IForOfState = { chunkSize : 6 , startIndex : 0 };
private currentVirtState: IForOfState = { chunkSize : 6 , startIndex : 0 };
private itemID = 1 ;
private itemCount: number = 0 ;
private hasSelection: boolean ;
private additionalScroll: number = 0 ;
constructor (
private remoteService: RemoteNWindService,
public cdr: ChangeDetectorRef
) { }
public ngOnInit ( ) {
this .rData = this .remoteService.remoteData;
}
public ngAfterViewInit ( ) {
const initSize = {
startIndex : 0 ,
chunkSize : Math .ceil(this .remoteSimpleCombo.itemsMaxHeight / this .remoteSimpleCombo.itemHeight)
};
this .remoteService.getData(initSize, null , (data ) => {
this .remoteSimpleCombo.totalItemCount = data['@odata.count' ];
this .itemCount = this .remoteSimpleCombo.totalItemCount;
});
}
public dataLoading ( ) {
if (this .prevRequest) {
this .prevRequest.unsubscribe();
}
this .loadingToast.positionSettings.verticalDirection = VerticalAlignment.Middle;
this .loadingToast.autoHide = false ;
this .loadingToast.open('Loading Remote Data...' );
this .cdr.detectChanges();
this .prevRequest = this .remoteService.getData(
this .remoteSimpleCombo.virtualizationState,
this .searchText,
(data ) => {
this .remoteSimpleCombo.totalItemCount = data['@odata.count' ];
this .loadingToast.close();
this .cdr.detectChanges();
}
);
}
public onOpened ( ) {
const scroll: number = this .remoteSimpleCombo.virtualScrollContainer.getScrollForIndex(this .itemID - 1 );
this .remoteSimpleCombo.virtualScrollContainer.scrollPosition = scroll + this .additionalScroll;
this .cdr.detectChanges();
}
public onClosing ( ) {
this .searchText = '' ;
}
public onClosed ( ) {
this .currentVirtState.startIndex = (this .itemID || 1 ) - 1 ;
this .remoteService.getData(
this .currentVirtState,
this .searchText,
(data ) => {
this .remoteSimpleCombo.totalItemCount = data['@odata.count' ];
this .cdr.detectChanges();
}
);
}
public handleSelectionChanging (evt: ISimpleComboSelectionChangingEventArgs ) {
this .hasSelection = evt.newValue !== undefined ;
if (!this .hasSelection) {
this .itemID = 1 ;
this .currentVirtState = this .defaultVirtState;
return ;
}
this .currentVirtState.chunkSize = Math .ceil(this .remoteSimpleCombo.itemsMaxHeight / this .remoteSimpleCombo.itemHeight);
this .itemCount === evt.newValue ?
this .additionalScroll = this .remoteSimpleCombo.itemHeight :
this .additionalScroll = 0 ;
if (this .itemCount - evt.newValue >= this .currentVirtState.chunkSize - 1 ) {
this .itemID = this .currentVirtState.startIndex = evt.newValue;
} else {
this .itemID = this .currentVirtState.startIndex = this .itemCount - (this .currentVirtState.chunkSize - 1 );
}
}
public handleSearchInputUpdate (searchData: IComboSearchInputEventArgs ) {
this .currentVirtState.startIndex = 0 ;
this .currentVirtState.chunkSize = Math .ceil(this .remoteSimpleCombo.itemsMaxHeight / this .remoteSimpleCombo.itemHeight);
this .searchText = searchData?.searchText || '' ;
this .remoteService.getData(
this .searchText ? this .currentVirtState : this .defaultVirtState,
this .searchText,
(data ) => {
this .remoteSimpleCombo.totalItemCount = data['@odata.count' ];
}
);
}
}
ts コピー <igx-simple-combo #remoteSimpleCombo class ="combo"
[itemsMaxHeight ]="250"
[itemHeight ]="48"
[data ]="rData | async"
[valueKey ]="'ProductID'"
[displayKey ]="'ProductName'"
placeholder ="Product"
(dataPreLoad )="dataLoading()"
(closing )="onClosing()" (opened )="onOpened()"
(closed )="onClosed()"
(selectionChanging )="handleSelectionChanging($event)"
(searchInputUpdate )="handleSearchInputUpdate($event)" >
</igx-simple-combo >
<igx-toast #loadingToast > </igx-toast >
html コピー .combo {
margin : 8px ;
width : 430px ;
}
scss コピー
스타일링
를 Ignite UI for Angular Theming
사용하여 간단한 콤보 상자 모양을 크게 변경할 수 있습니다. 먼저 테마 엔진에 의해 노출된 기능을 사용하려면 스타일 파일에 파일을 가져와야 index
합니다.
@use 'igniteui-angular/theming' as *;
scss
가장 간단한 접근 방식에 따라 매개 변수를 확장 combo-theme
하고 허용하는 새 테마를 만듭니다. $empty-list-background
$custom-simple-combo-theme : combo-theme(
$empty-list-background : #1a5214
);
scss
IgxSimpleComboComponent
내부적으로 항목 컨테이너로 사용합니다 IgxDropDownComponent
. 또한 구성 요소도 IgxInputGroup
포함됩니다. 이러한 구성 요소의 테마를 확장하는 새 테마를 만들고 해당 클래스 아래에 범위를 지정하면 간단한 콤보 상자 스타일을 변경할 수 있습니다.
$custom-drop-down-theme : drop-down-theme(
$background-color : #d9f5d6 ,
$header-text-color : #1a5214 ,
$item-text-color : #1a5214 ,
$focused-item-background : #72da67 ,
$focused-item-text-color : #1a5214 ,
$hover-item-background : #a0e698 ,
$hover-item-text-color : #1a5214 ,
$selected-item-background : #a0e698 ,
$selected-item-text-color : #1a5214 ,
$selected-hover-item-background : #72da67 ,
$selected-hover-item-text-color : #1a5214 ,
$selected-focus-item-background : #72da67 ,
$selected-focus-item-text-color : #1a5214 ,
);
scss
마지막 단계는 구성 요소의 테마를 포함하는 것입니다.
:host ::ng-deep {
@include css-vars($custom-combo-theme );
@include css-vars($custom-drop-down-theme );
}
scss
기본값 type
의 IgxSimpleCombo
다음과 같음 box
달리 IgxSelect
그것이 있는 곳 line
.
데모
import { Component, ElementRef, OnInit } from '@angular/core' ;
import { City, getCitiesByPopulation } from '../../../data/cities15000-regions-countries' ;
import { IgxSimpleComboComponent } from 'igniteui-angular' ;
@Component ({
selector : 'app-simple-combo-styling' ,
templateUrl : 'simple-combo-styling.component.html' ,
styleUrls : ['simple-combo-styling.component.scss' ],
imports : [IgxSimpleComboComponent]
})
export class SimpleComboStylingComponent implements OnInit {
public cities: City[];
constructor (public element: ElementRef ) { }
ngOnInit(): void {
this .cities = getCitiesByPopulation(10000000 );
}
}
ts コピー <div class ="sample-wrapper" >
<div class ="input-row" >
<igx-simple-combo
[overlaySettings ]="{ outlet: element.nativeElement }"
[data ]="cities" [displayKey ]="'name'" >
</igx-simple-combo >
</div >
</div >
html コピー @use "layout.scss" ;
@use "igniteui-angular/theming" as *;
$custom-simple-combo-theme : combo-theme(
$empty-list-background : #1a5214
);
$custom-drop-down-theme : drop-down-theme(
$background-color : #d9f5d6 ,
$header-text-color : #1a5214 ,
$item-text-color : #1a5214 ,
$focused-item-background : #72da67 ,
$focused-item-text-color : #1a5214 ,
$hover-item-background : #a0e698 ,
$hover-item-text-color : #1a5214 ,
$selected-item-background : #a0e698 ,
$selected-item-text-color : #1a5214 ,
$selected-hover-item-background : #72da67 ,
$selected-hover-item-text-color : #1a5214 ,
$selected-focus-item-background : #72da67 ,
$selected-focus-item-text-color : #1a5214 ,
);
:host ::ng-deep {
@include css-vars($custom-simple-combo-theme );
@include css-vars($custom-drop-down-theme );
}
scss コピー
알려진 문제
단순 콤보박스에는 높이 크기를 조정하기 위한 입력이 없습니다. 앞으로 IgxInputGroup 구성 요소는 사용자 정의 크기 조정을 허용하는 옵션을 제공할 것이며 IgxSimpleCombo 는 적절한 스타일 지정 및 더 나은 일관성을 위해 동일한 기능을 사용할 것입니다.
단순 콤보박스가 undefined
(예 [ undefined, ...]
) 포함된 기본 데이터 배열에 바인딩되면 undefined
드롭다운에 표시되지 않습니다. 복잡한 데이터(예: 개체)의 배열에 바인딩되어 있고 valueKey
에 사용된 값이 undefined
경우 해당 항목은 드롭다운에 표시되지만 선택할 수는 없습니다.
단순 콤보박스가 ngModel
통해 바인딩되고 required
로 표시되면 null
, undefined
및''
값을 선택할 수 없습니다.
단순 콤보 상자가 원격 서비스에 바인딩되어 있고 미리 정의된 선택 항목이 있는 경우 해당 입력은 요청된 데이터가 로드될 때까지 공백으로 유지됩니다.
단순 콤보 상자는 내부적으로 igxForOf
지시문을 사용하므로 모든 igxForOf
제한 사항은 단순 콤보 상자에 유효합니다. 자세한 내용은 igxForOf 알려진 문제 섹션을 참조하세요.
API 요약
사용된 관련 API가 포함된 추가 구성 요소 및/또는 지시어:
테마 종속성
추가 리소스
우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.