Angular Grid のソート
Ignite UI for Angular Grid では、列レベルでのデータ ソートが可能です。つまり、igx-grid にソート可能な列とソート不可の列の両方を持つことができます。Angular でソートを実行すると、指定した条件に基づいてレコードの表示順序を変更できます。
これまで、グループ化 / ソートは互いに連携して機能していました。13.2 バージョンでは、グループ化をソートから切り離す新しい動作が導入されています。たとえば、グループ化をクリアしても、グリッド内のソート式はクリアされません。その逆も同様です。それでも、列がソートおよびグループ化されている場合は、グループ化された式が優先されます。
Angular Grid ソートの例
import { NgModule } from "@angular/core" ;
import { FormsModule } from "@angular/forms" ;
import { BrowserModule } from "@angular/platform-browser" ;
import { BrowserAnimationsModule } from "@angular/platform-browser/animations" ;
import { AppComponent } from "./app.component" ;
import {
IgxGridModule,
IgxIconModule,
IgxRippleModule,
IgxInputGroupModule,
IgxSelectModule
} from "igniteui-angular" ;
import { SortingSampleComponent } from "./grid/grid-sorting-sample/grid-sorting-sample.component" ;
import { IgxPreventDocumentScrollModule } from "./directives/prevent-scroll.directive" ;
@NgModule ({
bootstrap : [AppComponent],
declarations : [
AppComponent,
SortingSampleComponent
],
imports : [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
IgxPreventDocumentScrollModule,
IgxGridModule,
IgxRippleModule,
IgxIconModule,
IgxInputGroupModule,
IgxSelectModule
],
providers : [],
entryComponents : [],
schemas : []
})
export class AppModule {}
ts コピー
import { Component, OnInit, ViewChild } from '@angular/core' ;
import { DefaultSortingStrategy, IgxGridComponent, ISortingOptions, SortingDirection } from 'igniteui-angular' ;
import { DATA } from '../../data/localData' ;
@Component ({
selector : 'app-grid-sample' ,
styleUrls : ['./grid-sorting-sample.component.scss' ],
templateUrl : 'grid-sorting-sample.component.html'
})
export class SortingSampleComponent implements OnInit {
@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;
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 ="raised" (click )="grid1.sortingExpressions = []" >
Clear Sorting
</button >
<button class ="button-opitions" igxButton ="raised" (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 コピー .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
入力で可能です。Grid のソートで、sortingIgnoreCase
プロパティを設定して大文字と小文字を区別するソートができます。
<igx-column field ="ProductName" header ="Product Name" [dataType ]="'string'" sortable ="true" > </igx-column >
html
ソート インジケーター
ソートされた列数が一定数以上ある場合、ソート順の指定がないと混乱する可能性があります。
IgxGrid は、ソートされた各列のインデックスを示すことにより、この問題の解決策を提供します。
import { NgModule } from "@angular/core" ;
import { FormsModule } from "@angular/forms" ;
import { BrowserModule } from "@angular/platform-browser" ;
import { BrowserAnimationsModule } from "@angular/platform-browser/animations" ;
import { AppComponent } from "./app.component" ;
import { GridSortingIndicatorsComponent } from "./grid/grid-sorting-indicators/grid-sorting-indicators.component" ;
import { IgxGridModule } from "igniteui-angular" ;
import { IgxPreventDocumentScrollModule } from "./directives/prevent-scroll.directive" ;
@NgModule ({
bootstrap : [AppComponent],
declarations : [
AppComponent,
GridSortingIndicatorsComponent
],
imports : [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
IgxPreventDocumentScrollModule,
IgxGridModule
],
providers : [],
entryComponents : [],
schemas : []
})
export class AppModule {}
ts コピー import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core' ;
import { IgxGridComponent, DefaultSortingStrategy } from 'igniteui-angular' ;
import { FinancialData } from '../../data/financialData' ;
import {generateRandomInteger, generateRandomFloat} from '../../data/utils' ;
@Component ({
selector : 'app-grid-sorting-indicators' ,
templateUrl : './grid-sorting-indicators.component.html' ,
styleUrls : ['./grid-sorting-indicators.component.scss' ]
})
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
メソッドを使用して列、複数の列の組み合わせをソートできます。
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 の基になるデータ ソースは変更しません 。
初期のソート状態
Grid でソート状態を初期設定するには、ソート式の配列を Grid の sortingExpressions
プロパティに渡します。
public ngAfterViewInit(): void {
this .grid.sortingExpressions = [
{
dir : SortingDirection.Asc, fieldName : 'CategoryName' ,
ignoreCase : true , strategy : DefaultSortingStrategy.instance()
}
];
}
typescript
string
型の値が dataType
Date
の列で使用される場合、Grid が値を Date
オブジェクトに解析しないため iGrid sorting
が正しく動作しません。string
オブジェクトを使用する場合、値を Date
オブジェクトに解析するためのロジックをアプリケーション レベルで実装する必要があります。
リモート ソート
Grid はリモート ソートをサポートします。詳細については、Grid リモート データ操作
で説明されています。
ソート インジケーのターテンプレート
列ヘッダーのソート インジケーター アイコンは、テンプレートを使用してカスタマイズできます。以下のディレクティブは、ソート状態 (昇順、降順、なし) のソート インジケーターをテンプレート化するために使用できます。
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
上記のようにカラーの値をハードコーディングする代わりに、palette
および color
関数を使用してカラーに関してより高い柔軟性を実現することができます。使い方の詳細についてはパレット
のトピックをご覧ください。
最後の手順は、それぞれのテーマを持つコンポーネント ミックスインを含める ことです。
@include css-vars($custom-theme );
scss
デモ
import { NgModule } from "@angular/core" ;
import { FormsModule } from "@angular/forms" ;
import { BrowserModule } from "@angular/platform-browser" ;
import { BrowserAnimationsModule } from "@angular/platform-browser/animations" ;
import { AppComponent } from "./app.component" ;
import {
IgxGridModule,
IgxIconModule,
IgxRippleModule,
IgxInputGroupModule,
IgxSelectModule
} from "igniteui-angular" ;
import { SortingStylingComponent } from "./grid/grid-sorting-styling/grid-sorting-styling.component" ;
import { IgxPreventDocumentScrollModule } from "./directives/prevent-scroll.directive" ;
@NgModule ({
bootstrap : [AppComponent],
declarations : [
AppComponent,
SortingStylingComponent
],
imports : [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
IgxPreventDocumentScrollModule,
IgxGridModule,
IgxRippleModule,
IgxIconModule,
IgxInputGroupModule,
IgxSelectModule
],
providers : [],
entryComponents : [],
schemas : []
})
export class AppModule {}
ts コピー
import { Component, OnInit, ViewChild } from '@angular/core' ;
import { DefaultSortingStrategy, IgxGridComponent, IgxSelectComponent, SortingDirection } from 'igniteui-angular' ;
import { DATA } from '../../data/localData' ;
enum TYPE {
SINGLE = 'single' ,
MULTI = 'multiple'
}
@Component ({
selector : 'app-grid-sorting-styling' ,
styleUrls : ['./grid-sorting-styling.component.scss' ],
templateUrl : 'grid-sorting-styling.component.html'
})
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 >
<igx-select-item *ngFor ="let type of sortingTypes" [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 '../../../variables' as *;
$custom-theme : grid-theme(
$sorted-header-icon-color : #ffb06a ,
$sortable-header-icon-hover-color : black
);
:host ::ng-deep {
@include css-vars($custom-theme );
}
.grid__wrapper {
margin : 0 auto;
padding : 16px ;
}
scss コピー
このサンプルは、Change Theme
(テーマの変更) から選択したグローバル テーマに影響を受けません。
API リファレンス
その他のリソース
コミュニティに参加して新しいアイデアをご提案ください。