[Angular] 於Kendo Grid 同時加入sort 及 page

Kendo UI 是由Telerik 開發的一套Web UI 套件. 使用它主要是因為它強大的後台Microsoft 支撐. 而這幾年, 它亦開始了Angular 的開發. 然而, 其功能若跟WPF control 比較, 則有得多要改善的地方. 而在示範中, 則補元了datagrid 中出了page 後sorting 的功能. 方法如下.

app-report.component.html

<div>
<kendo-grid [data]="orderGridDataResult"
                    [sortable]="true"
                    [pageable]="true"
                    [pageSize]="pageSize"
                    [skip]="skip"
                    [height]="600"
                    [scrollable]="'Scrollable'"
                    (pageChange)="pageChange($event)"
                    [sort]="sort"
                    (sortChange)="sortChange($event)"
                    >
                    </kendo-grid>
</div>

app-report.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { AppSettings } from '../../app.settings';
import { Order } from '../roi-order';
import { RoiService } from '../roi.service';
import { GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid';
import { SortDescriptor, orderBy } from '@progress/kendo-data-query';

@Component({
  selector: 'app-regular-report',
  templateUrl: './report.component.html',
  styleUrls: ['./report.component.scss'],
  providers: [RoiService]
})
export class RoiRegularReportComponent implements AfterViewInit {
  public orders: Array<Order>;

  public orderGridDataResult: GridDataResult;
  public skip = 0;
  public pageSize = 10;
  public sort: SortDescriptor[] = [{
    field: 'OrderID',
    dir: 'asc'
  }];

  public reportHTML: string;

  constructor(private roiService: RoiService) {
    this.resetCommand();
  }
  ngAfterViewInit() {
  }

  public pageChange(event: PageChangeEvent): void {
    this.skip = event.skip;
    this.loadItems();
  }

  private loadItems(): void {
    this.orderGridDataResult = {
      data: this.handleData(),
      total: this.orders.length
    };
  }

  public sortChange(sort: SortDescriptor[]): void {
    this.sort = sort;
    this.loadItems();
  }
  private handleData() {
    let orderedData = this.orders;
    if (this.sort) {
      orderedData = orderBy(this.orders, this.sort);
    }
    const orderedAndPagedData = orderedData.slice(this.skip, this.skip + this.pageSize);
    return orderedAndPagedData;
  }
}

於component.ts 中, 建立了另一variable GridDataResult 去與UI 進行binding. 當TypeScript接了page 及sort 的event後, 便會重新sort 後再將它分page. 從而避免descending order 時sorting 出錯.

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.