Angular Tree Grid Sorting
Ignite UI for Angular에서 데이터 정렬은 열 단위로 활성화되어 igx-tree-grid에 정렬 가능한 열과 정렬 불가능한 열이 혼합될 수 있습니다. 각도 정렬 작업을 수행하면 지정된 기준에 따라 레코드의 표시 순서를 변경할 수 있습니다.
지금까지는 그룹화/정렬이 서로 함께 작동했습니다. 13.2 버전에서는 정렬에서 그룹화를 분리하는 새로운 동작이 도입되었습니다. 예를 들어 그룹화를 지우면 그리드의 정렬 표현식이 지워지지 않으며 그 반대의 경우도 마찬가지입니다. 그러나 열이 정렬되고 그룹화된 경우 그룹화된 식이 우선합니다.
Angular Tree Grid Sorting Overview Example
또한 igx-tree-grid 의 출력을 사용하여 정렬하기 위해 사용자 정의 컨텍스트 메뉴가 contextMenu
추가되었습니다.
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core' ;
import { DefaultSortingStrategy, IgxTreeGridComponent, ISortingOptions, SortingDirection, IgxGridToolbarComponent, IgxButtonDirective, IgxGridToolbarActionsComponent, IgxSimpleComboComponent, IgxComboClearIconDirective, IgxComboItemDirective, IgxTreeGridGroupByAreaComponent, IgxColumnComponent, IgxCellTemplateDirective } from 'igniteui-angular' ;
import { ORDERS_DATA } from '../data/orders' ;
import { IgxPreventDocumentScrollDirective } from '../directives/prevent-scroll.directive' ;
import { FormsModule } from '@angular/forms' ;
import { UpperCasePipe } from '@angular/common' ;
import { TreeGridContextmenuComponent } from '.tree-grid-contextmenu/tree-grid-contextmenu.component' ;
@Component ({
selector : 'app-tree-grid-sorting-sample' ,
styleUrls : ['./tree-grid-sorting-sample.component.scss' ],
templateUrl : 'tree-grid-sorting-sample.component.html' ,
imports : [IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxGridToolbarComponent, IgxButtonDirective, IgxGridToolbarActionsComponent, IgxSimpleComboComponent, FormsModule, IgxComboClearIconDirective, IgxComboItemDirective, IgxTreeGridGroupByAreaComponent, IgxColumnComponent, IgxCellTemplateDirective, TreeGridContextmenuComponent, UpperCasePipe]
})
export class TreeGridSortingSampleComponent implements OnInit , AfterViewInit {
@ViewChild ('treegrid1' , { read : IgxTreeGridComponent, static : true })
public treegrid1: IgxTreeGridComponent;
public data: any [];
public contextmenu = false ;
public contextmenuX = 0 ;
public contextmenuY = 0 ;
public clickedCell = null ;
public sortingTypes: ISortingOptions[] = [
{
mode : 'single'
}, {
mode : 'multiple'
}
];
public sortingOptions: ISortingOptions = this .sortingTypes[1 ];
public options = {
digitsInfo : '1.2-2' ,
currencyCode : 'USD'
};
public formatOptions = this .options;
constructor ( ) { }
public ngOnInit(): void {
this .data = ORDERS_DATA;
}
public ngAfterViewInit(): void {
this .treegrid1.sortingExpressions = [
{ dir : SortingDirection.Asc, fieldName : 'UnitPrice' ,
ignoreCase : true , strategy : DefaultSortingStrategy.instance() }
];
}
public formatDate (val: Date ) {
return new Intl .DateTimeFormat('en-US' ).format(val);
}
public rightClick (eventArgs ) {
eventArgs.event.preventDefault();
this .contextmenuX = eventArgs.event.clientX;
this .contextmenuY = eventArgs.event.clientY;
this .contextmenu = true ;
this .clickedCell = eventArgs.cell;
}
public disableContextMenu ( ) {
this .contextmenu = false ;
}
handleSearchResults (event: KeyboardEvent ) {
event.preventDefault();
}
}
ts コピー <div class ="grid__wrapper" (window:click )="disableContextMenu()" >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treegrid1 [data ]="data" [autoGenerate ]="false" height ="500px" width ="100%"
primaryKey ="ID" foreignKey ="ParentID" (contextMenu )="rightClick($event)" [sortingOptions ]="sortingOptions" >
<igx-grid-toolbar >
<button class ="button-opitions" igxButton ="contained" (click )="treegrid1.sortingExpressions = []" >
Clear Sorting
</button >
<button class ="button-opitions" igxButton ="contained" (click )="groupArea.expressions = []" >
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-tree-grid-group-by-area
#groupArea
[grid ]="treegrid1"
[hideGroupedColumns ]="true" >
</igx-tree-grid-group-by-area >
<igx-column field ="ID" header ="Order ID" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="Name" header ="Order Product" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="Category" header ="Category" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="Units" header ="Units" [dataType ]="'number'" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="UnitPrice" header ="Unit Price" [dataType ]="'currency'" [pipeArgs ]="formatOptions" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="Price" header ="Price" [dataType ]="'currency'" [pipeArgs ]="formatOptions" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="OrderDate" header ="Order Date" [dataType ]="'date'" [formatter ]="formatDate" [groupable ]="true" [sortable ]="true" >
</igx-column >
<igx-column field ="Delivered" header ="Delivered" [dataType ]="'boolean'" [groupable ]="true" [sortable ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
@if (val) {
<img src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/active.png" title ="Delivered" alt ="Delivered" />
}
@if (!val) {
<img src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/expired.png" title ="Undelivered" alt ="Undelivered" />
}
</ng-template >
</igx-column >
</igx-tree-grid >
@if (contextmenu) {
<div >
<app-tree-grid-contextmenu [x ]="contextmenuX" [y ]="contextmenuY" [cell ]="clickedCell" > </app-tree-grid-contextmenu >
</div >
}
</div >
html コピー .grid__wrapper {
--ig-size: var(--ig-size-small);
margin : 0 16px ;
padding-top : 16px ;
}
.igx-grid-toolbar ::ng-deep {
.igx-grid-toolbar__custom-content {
display: flex;
flex-direction : row;
justify-content : flex-start;
}
}
scss コピー
Like this sample? Get access to our complete Ignite UI for Angular toolkit and start building your own apps in minutes. Download it for free.
이는 sortable
입력을 통해 수행됩니다. 트리 그리드 정렬을 사용하면 sortingIgnoreCase
속성을 설정하여 대소문자 구분 정렬을 수행할 수도 있습니다.
<igx-column field ="Name" header ="Order Product" [dataType ]="'string'" sortable ="true" > </igx-column >
html
Sorting Indicators
정렬된 순서가 표시되지 않으면 일정량의 열이 정렬되어 있으면 정말 혼란스러울 수 있습니다.
IgxTreeGrid 는 정렬된 각 열의 인덱스를 표시하여 이 문제에 대한 솔루션을 제공합니다.
Sorting through the API
Tree Grid sort
방법을 사용하여 Tree Grid API를 통해 모든 열 또는 열 조합을 정렬할 수 있습니다.
import { SortingDirection } from 'igniteui-angular' ;
this .treeGrid.sort({ fieldName : 'Name' , dir : SortingDirection.Asc, ignoreCase : true });
this .treeGrid.sort([
{ fieldName : 'Name' , dir : SortingDirection.Asc, ignoreCase : true },
{ fieldName : 'UnitPrice' , dir : SortingDirection.Desc }
]);
typescript
필터링 동작과 마찬가지로 clearSort
메서드를 사용하여 정렬 상태를 지울 수 있습니다.
this .treeGrid.clearSort('Name' );
this .treeGrid.clearSort();
typescript
정렬 작업은 트리 그리드의 기본 데이터 소스를 변경 하지 않습니다 .
Initial sorting state
정렬 표현식의 배열을 트리 그리드의 sortingExpressions
속성에 전달하여 트리 그리드의 초기 정렬 상태를 설정할 수 있습니다.
public ngAfterViewInit(): void {
this .treeGrid.sortingExpressions = [
{
dir : SortingDirection.Asc, fieldName : 'UnitPrice' ,
ignoreCase : true , strategy : DefaultSortingStrategy.instance()
}
];
}
typescript
string
유형의 값이 dataType
Date
열에서 사용되는 경우 트리 그리드는 해당 값을 Date
객체로 구문 분석하지 않으며 트리 그리드 sorting
사용하면 예상대로 작동하지 않습니다. string
객체를 사용하려면 값을 Date
객체로 구문 분석하기 위해 애플리케이션 수준에서 추가 논리를 구현해야 합니다.
Sorting Indicators Templates
열 머리글의 정렬 표시기 아이콘은 템플릿을 사용하여 사용자 정의할 수 있습니다. 모든 정렬 상태(오름차순, 내림차순, 없음)에 대한 정렬 표시기 템플릿을 작성하는 데 다음 지시문을 사용할 수 있습니다.
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
Demo
import { Component, OnInit, ViewChild } from '@angular/core' ;
import { DefaultSortingStrategy, IgxTreeGridComponent, SortingDirection, IgxColumnComponent, IgxCellTemplateDirective } from 'igniteui-angular' ;
import { ORDERS_DATA } from '../data/orders' ;
import { IgxPreventDocumentScrollDirective } from '../directives/prevent-scroll.directive' ;
@Component ({
selector : 'app-tree-grid-sorting-styling' ,
styleUrls : ['./tree-grid-sorting-styling.component.scss' ],
templateUrl : 'tree-grid-sorting-styling.component.html' ,
imports : [IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxCellTemplateDirective]
})
export class TreeGridSortingStylingComponent implements OnInit {
@ViewChild ('treegrid1' , { read : IgxTreeGridComponent, static : true })
public treegrid1: IgxTreeGridComponent;
public data: any [];
public options = {
digitsInfo : '1.2-2' ,
currencyCode : 'USD'
};
public formatOptions = this .options;
constructor ( ) {
}
public ngOnInit(): void {
this .data = ORDERS_DATA;
this .treegrid1.sortingExpressions = [
{ dir : SortingDirection.Asc, fieldName : 'UnitPrice' ,
ignoreCase : true , strategy : DefaultSortingStrategy.instance() }
];
}
public formatDate (val: Date ) {
return new Intl .DateTimeFormat('en-US' ).format(val);
}
}
ts コピー <div class ="grid__wrapper" >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treegrid1 [data ]="data" [autoGenerate ]="false" height ="500px" width ="100%" primaryKey ="ID"
foreignKey ="ParentID" >
<igx-column field ="ID" header ="Order ID" [sortable ]="true" >
</igx-column >
<igx-column field ="Name" header ="Order Product" [sortable ]="true" >
</igx-column >
<igx-column field ="Category" header ="Category" [sortable ]="true" >
</igx-column >
<igx-column field ="Units" header ="Units" [dataType ]="'number'" [sortable ]="true" >
</igx-column >
<igx-column field ="UnitPrice" header ="Unit Price" [dataType ]="'currency'" [pipeArgs ]="formatOptions" [sortable ]="true" >
</igx-column >
<igx-column field ="OrderDate" header ="Order Date" [dataType ]="'date'" [formatter ]="formatDate"
[sortable ]="true" >
</igx-column >
<igx-column field ="Delivered" header ="Delivered" [dataType ]="'boolean'" [groupable ]="true" [sortable ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
@if (val) {
<img src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/active.png" title ="Delivered" alt ="Delivered" />
}
@if (!val) {
<img src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/expired.png" title ="Undelivered" alt ="Undelivered" />
}
</ng-template >
</igx-column >
</igx-tree-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 References
Additional Resources
우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.