Angular 그리드 정렬
Ignite UI for Angular에서 데이터 정렬은 열 단위로 활성화되어 igx-grid에 정렬 가능한 열과 정렬 불가능한 열이 혼합될 수 있습니다. 각도 정렬 작업을 수행하면 지정된 기준에 따라 레코드의 표시 순서를 변경할 수 있습니다.
지금까지는 그룹화/정렬이 서로 함께 작동했습니다. 13.2 버전에서는 정렬에서 그룹화를 분리하는 새로운 동작이 도입되었습니다. 예를 들어 그룹화를 지우면 그리드의 정렬 표현식이 지워지지 않으며 그 반대의 경우도 마찬가지입니다. 그러나 열이 정렬되고 그룹화된 경우 그룹화된 식이 우선합니다.
Angular 그리드 정렬 개요 예
import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core' ;
import { DefaultSortingStrategy, IgxGridComponent, ISortingOptions, SortingDirection, IgxGridToolbarComponent, IgxButtonDirective, IgxGridToolbarActionsComponent, IgxSimpleComboComponent, IgxComboClearIconDirective, IgxComboItemDirective, IgxColumnComponent, IgxCellTemplateDirective } from 'igniteui-angular' ;
import { DATA } from '../../data/localData' ;
import { IgxPreventDocumentScrollDirective } from '../../directives/prevent-scroll.directive' ;
import { FormsModule } from '@angular/forms' ;
import { UpperCasePipe } from '@angular/common' ;
@Component ({
selector : 'app-grid-sample' ,
styleUrls : ['./grid-sorting-sample.component.scss' ],
templateUrl : 'grid-sorting-sample.component.html' ,
imports : [IgxGridComponent, IgxPreventDocumentScrollDirective, IgxGridToolbarComponent, IgxButtonDirective, IgxGridToolbarActionsComponent, IgxSimpleComboComponent, FormsModule, IgxComboClearIconDirective, IgxComboItemDirective, IgxColumnComponent, IgxCellTemplateDirective, UpperCasePipe]
})
export class SortingSampleComponent implements OnInit , AfterViewInit {
@ViewChild ('grid1' , { read : IgxGridComponent, static : true })
public grid1: IgxGridComponent;
public data: any [];
public sortingTypes: ISortingOptions[] = [
{
mode : 'single'
}, {
mode : 'multiple'
}
];
public sortingOptions: ISortingOptions = this .sortingTypes[1 ];
constructor ( ) { }
public ngOnInit(): void {
this .data = DATA;
}
public ngAfterViewInit(): void {
this .grid1.sortingExpressions = [
{
dir : SortingDirection.Asc, fieldName : 'CategoryName' ,
ignoreCase : true , strategy : DefaultSortingStrategy.instance()
}
];
}
public formatDate (val: Date ) {
return new Intl .DateTimeFormat('en-US' ).format(val);
}
handleSearchResults (event: KeyboardEvent ) {
event.preventDefault();
}
}
ts コピー <div class ="grid__wrapper" >
<igx-grid [igxPreventDocumentScroll ]="true" #grid1 [data ]="data" [autoGenerate ]="false" height ="500px" width ="100%" [sortingOptions ]="sortingOptions" >
<igx-grid-toolbar >
<button class ="button-opitions" igxButton ="contained" (click )="grid1.sortingExpressions = []" >
Clear Sorting
</button >
<button class ="button-opitions" igxButton ="contained" (click )="grid1.groupingExpressions = []" >
Clear Grouped columns
</button >
<igx-grid-toolbar-actions >
<igx-simple-combo #comboItem
[data ]="sortingTypes"
[displayKey ]="'mode'"
[(ngModel )]="sortingOptions"
(keydown )="handleSearchResults($event)" >
<ng-template igxComboClearIcon > </ng-template >
<ng-template igxComboItem let-item >
<div > {{ item.mode | uppercase }}</div >
</ng-template >
</igx-simple-combo >
</igx-grid-toolbar-actions >
</igx-grid-toolbar >
<igx-column field ="OrderID" header ="Order ID" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="CategoryName" header ="Category Name" [dataType ]="'string'" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="CompanyName" header ="Company Name" [dataType ]="'string'" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="ShipCountry" header ="Ship Country" [dataType ]="'string'" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="SaleAmount" header ="Sale Amount" dataType ="number" [groupable ]="true" [sortable ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
${{val}}
</ng-template >
</igx-column >
<igx-column field ="ShippedDate" header ="Shipped Date" [dataType ]="'date'" [formatter ]="formatDate" [sortable ]="true" >
</igx-column >
</igx-grid >
</div >
html コピー igx-simple-combo {
--ig-size: var(--ig-size-small);
}
.grid__wrapper {
margin : 0 auto;
padding : 16px ;
}
.igx-grid-toolbar ::ng-deep {
.igx-grid-toolbar__custom-content {
display: flex;
flex-direction : row;
justify-content : flex-start;
}
}
scss コピー
이 샘플이 마음에 드시나요? 전체 Ignite UI for Angular 툴킷에 액세스하고 몇 분 안에 나만의 앱을 구축해 보세요. 무료로 다운로드하세요.
이는 sortable
입력을 통해 수행됩니다. 그리드 정렬을 사용하면 sortingIgnoreCase
속성을 설정하여 대소문자 구분 정렬을 수행할 수도 있습니다.
<igx-column field ="ProductName" header ="Product Name" [dataType ]="'string'" sortable ="true" > </igx-column >
html
지표 정렬
정렬된 순서가 표시되지 않으면 일정량의 열이 정렬되어 있으면 정말 혼란스러울 수 있습니다.
IgxGrid 는 정렬된 각 열의 인덱스를 표시하여 이 문제에 대한 솔루션을 제공합니다.
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core' ;
import { IgxGridComponent, DefaultSortingStrategy, IgxColumnComponent } from 'igniteui-angular' ;
import { FinancialData } from '../../data/financialData' ;
import {generateRandomInteger, generateRandomFloat} from '../../data/utils' ;
import { IgxPreventDocumentScrollDirective } from '../../directives/prevent-scroll.directive' ;
@Component ({
selector : 'app-grid-sorting-indicators' ,
templateUrl : './grid-sorting-indicators.component.html' ,
styleUrls : ['./grid-sorting-indicators.component.scss' ],
imports : [IgxGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent]
})
export class GridSortingIndicatorsComponent implements OnInit , AfterViewInit {
@ViewChild ('grid1' , { static : true }) public grid: IgxGridComponent;
public data;
public ngOnInit(): void {
const typeArr = ['Gold' , 'Silver' , 'Coal' ];
this .data = FinancialData.generateData(1000 ).map(dataObj => {
const type = typeArr[generateRandomInteger(0 , 2 )];
switch (type ) {
case 'Gold' :
dataObj['Type' ] = 'Gold' ;
dataObj['Price' ] = generateRandomFloat(1261.78 , 1302.76 );
dataObj['Buy' ] = generateRandomFloat(1261.78 , 1280.73 );
break ;
case 'Silver' :
dataObj['Type' ] = 'Silver' ;
dataObj['Price' ] = generateRandomFloat(17.12 , 17.73 );
dataObj['Buy' ] = generateRandomFloat(17.12 , 17.43 );
break ;
case 'Coal' :
dataObj['Type' ] = 'Coal' ;
dataObj['Price' ] = generateRandomFloat(0.40 , 0.42 );
dataObj['Buy' ] = generateRandomFloat(0.42 , 0.46 );
break ;
}
return dataObj;
});
}
public ngAfterViewInit ( ) {
const expressions = [];
this .grid.columns.forEach(c => {
const sortExpr =
{
dir : generateRandomInteger(1 , 2 ), fieldName : c.field,
ignoreCase : true , strategy : DefaultSortingStrategy.instance()
};
expressions.push(sortExpr);
});
this .grid.sortingExpressions = expressions;
this .grid.cdr.detectChanges();
}
public formatCurrency (value: number ) {
return '$' + value.toFixed(2 );
}
}
ts コピー <div class ="grid__wrapper" >
<igx-grid [igxPreventDocumentScroll ]="true" #grid1 [data ]="data" [height ]="'500px'" width ="100%" >
<igx-column [sortable ]="true" [field ]="'Settlement'" > </igx-column >
<igx-column [sortable ]="true" [field ]="'Type'" > </igx-column >
<igx-column [sortable ]="true" [field ]="'Region'" > </igx-column >
<igx-column [sortable ]="true" [field ]="'Country'" > </igx-column >
<igx-column [sortable ]="true" [field ]="'Price'" dataType ="number" [formatter ]="formatCurrency" > </igx-column >
<igx-column [sortable ]="true" [field ]="'Buy'" dataType ="number" [formatter ]="formatCurrency" >
</igx-column >
</igx-grid >
</div >
html コピー .grid__wrapper {
margin : 0 auto;
padding : 16px ;
}
scss コピー
API를 통한 정렬
Grid sort
방법을 사용하여 Grid API를 통해 모든 열 또는 열 조합을 정렬할 수 있습니다.
import { SortingDirection } from 'igniteui-angular' ;
this .grid.sort({ fieldName : 'ProductName' , dir : SortingDirection.Asc, ignoreCase : true });
this .grid.sort([
{ fieldName : 'ProductName' , dir : SortingDirection.Asc, ignoreCase : true },
{ fieldName : 'Price' , dir : SortingDirection.Desc }
]);
typescript
필터링 동작과 마찬가지로 clearSort
메서드를 사용하여 정렬 상태를 지울 수 있습니다.
this .grid.clearSort('ProductName' );
this .grid.clearSort();
typescript
정렬 작업은 그리드의 기본 데이터 소스를 변경 하지 않습니다 .
초기 정렬 상태
정렬 표현식의 배열을 Grid의 sortingExpressions
속성에 전달하여 Grid의 초기 정렬 상태를 설정할 수 있습니다.
public ngAfterViewInit(): void {
this .grid.sortingExpressions = [
{
dir : SortingDirection.Asc, fieldName : 'CategoryName' ,
ignoreCase : true , strategy : DefaultSortingStrategy.instance()
}
];
}
typescript
string
유형의 값이 dataType
Date
열에서 사용되는 경우 Grid는 해당 값을 Date
객체로 구문 분석하지 않으며 Grid sorting
사용하면 예상대로 작동하지 않습니다. string
객체를 사용하려면 값을 Date
객체로 구문 분석하기 위해 애플리케이션 수준에서 추가 논리를 구현해야 합니다.
원격 정렬
그리드는 Grid Remote Data Operations
항목에 설명된 원격 정렬을 지원합니다.
지표 템플릿 정렬
열 머리글의 정렬 표시기 아이콘은 템플릿을 사용하여 사용자 정의할 수 있습니다. 모든 정렬 상태(오름차순, 내림차순, 없음)에 대한 정렬 표시기 템플릿을 작성하는 데 다음 지시문을 사용할 수 있습니다.
IgxSortHeaderIconDirective
– 정렬이 적용되지 않은 경우 정렬 아이콘의 템플릿을 다시 지정합니다.
<ng-template igxSortHeaderIcon >
<igx-icon > unfold_more</igx-icon >
</ng-template >
html
IgxSortAscendingHeaderIconDirective
– 열이 오름차순으로 정렬될 때 정렬 아이콘의 템플릿을 다시 지정합니다.
<ng-template igxSortAscendingHeaderIcon >
<igx-icon > expand_less</igx-icon >
</ng-template >
html
IgxSortDescendningHeaderIconDirective
– 열이 내림차순으로 정렬될 때 정렬 아이콘의 템플릿을 다시 지정합니다.
<ng-template igxSortDescendingHeaderIcon >
<igx-icon > expand_more</igx-icon >
</ng-template >
html
스타일링
정렬 동작 스타일 지정을 시작하려면 모든 테마 기능과 구성 요소 믹스인이 있는 index
파일을 가져와야 합니다.
@use "igniteui-angular/theming" as *;
scss
가장 간단한 접근 방식에 따라 grid-theme
확장하고 $sorted-header-icon-color
및 sortable-header-icon-hover-color
매개 변수를 허용하는 새로운 테마를 만듭니다.
$custom-theme : grid-theme(
$sorted-header-icon-color : #ffb06a ,
$sortable-header-icon-hover-color : black
);
scss
우리가 방금 한 것처럼 색상 값을 하드 코딩하는 대신, and color
함수를 사용하여 palette
색상 측면에서 더 큰 유연성을 얻을 수 있습니다. 사용 방법에 대한 자세한 지침은 항목을 참조하십시오 Palettes
.
마지막 단계는 구성요소 믹스인을 포함하는 것입니다.
@include css-vars($custom-theme );
scss
데모
import { Component, OnInit, ViewChild } from '@angular/core' ;
import { DefaultSortingStrategy, IgxGridComponent, IgxSelectComponent, SortingDirection, IgxGridToolbarComponent, IgxLabelDirective, IgxSelectItemComponent, IgxColumnComponent, IgxCellTemplateDirective } from 'igniteui-angular' ;
import { DATA } from '../../data/localData' ;
import { IgxPreventDocumentScrollDirective } from '../../directives/prevent-scroll.directive' ;
import { FormsModule } from '@angular/forms' ;
enum TYPE {
SINGLE = 'single' ,
MULTI = 'multiple'
}
@Component ({
selector : 'app-grid-sorting-styling' ,
styleUrls : ['./grid-sorting-styling.component.scss' ],
templateUrl : 'grid-sorting-styling.component.html' ,
imports : [IgxGridComponent, IgxPreventDocumentScrollDirective, IgxGridToolbarComponent, IgxSelectComponent, FormsModule, IgxLabelDirective, IgxSelectItemComponent, IgxColumnComponent, IgxCellTemplateDirective]
})
export class SortingStylingComponent implements OnInit {
@ViewChild ('grid1' , { read : IgxGridComponent, static : true })
public grid1: IgxGridComponent;
@ViewChild (IgxSelectComponent)
public igxSelect: IgxSelectComponent;
public data: any [];
public sortingTypes = [{ name : 'Multiple Sort' , value : TYPE.MULTI }, { name : 'Single Sort' , value : TYPE.SINGLE }];
public currentSortingType: TYPE = TYPE.SINGLE;
constructor ( ) {
}
public ngOnInit(): void {
this .data = DATA;
this .grid1.sortingExpressions = [
{
dir : SortingDirection.Asc, fieldName : 'CategoryName' ,
ignoreCase : true , strategy : DefaultSortingStrategy.instance()
}
];
}
public formatDate (val: Date ) {
return new Intl .DateTimeFormat('en-US' ).format(val);
}
public removeSorting ($event ) {
if (this .currentSortingType === TYPE.SINGLE) {
this .grid1.columns.forEach((col ) => {
if (!(col.field === $event.fieldName)) {
this .grid1.clearSort(col.field);
}
});
}
}
public sortTypeSelection (event ) {
this .grid1.clearSort();
}
}
ts コピー <div class ="grid__wrapper" >
<igx-grid [igxPreventDocumentScroll ]="true" #grid1 [data ]="data" [autoGenerate ]="false" height ="500px" width ="100%"
(sortingDone )="removeSorting($event)" >
<igx-grid-toolbar >
<igx-select [(ngModel )]="currentSortingType" (selectionChanging )="sortTypeSelection($event)" >
<label igxLabel > Select Sorting Type</label >
@for (type of sortingTypes; track type) {
<igx-select-item [value ]="type.value" >
{{type.name}}
</igx-select-item >
}
</igx-select >
</igx-grid-toolbar >
<igx-column field ="OrderID" header ="Order ID" >
</igx-column >
<igx-column field ="CategoryName" header ="Category Name" [dataType ]="'string'" [sortable ]="true" >
</igx-column >
<igx-column field ="CompanyName" header ="Company Name" [dataType ]="'string'" [sortable ]="true" >
</igx-column >
<igx-column field ="ShipCountry" header ="Ship Country" [dataType ]="'string'" [sortable ]="true" >
</igx-column >
<igx-column field ="SaleAmount" header ="Sale Amount" dataType ="number" [sortable ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
${{val}}
</ng-template >
</igx-column >
<igx-column field ="ShippedDate" header ="Shipped Date" [dataType ]="'date'" [formatter ]="formatDate"
[sortable ]="true" >
</igx-column >
</igx-grid >
</div >
html コピー @use "layout.scss" ;
@use "igniteui-angular/theming" as *;
$custom-theme : grid-theme(
$sorted-header-icon-color : #ffb06a ,
$sortable-header-icon-hover-color : black
);
@include css-vars($custom-theme );
scss コピー
샘플은 Change Theme
에서 선택한 전역 테마의 영향을 받지 않습니다.
API 참조
추가 리소스
우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.