1
+ import { Directive , Input , EventEmitter , SimpleChange , OnChanges , DoCheck } from "angular2/core" ;
2
+
3
+ export interface SortEvent {
4
+ sortBy : string ;
5
+ sortOrder : string
6
+ }
7
+
8
+ export interface PageEvent {
9
+ activePage : number ;
10
+ rowsOnPage : number ;
11
+ dataLength : number ;
12
+ }
13
+
14
+ export interface DataEvent {
15
+ length : number ;
16
+ }
17
+
18
+ @Directive ( {
19
+ selector : 'table[mfData]' ,
20
+ exportAs : 'mfDataTable'
21
+ } )
22
+ export class DataTable implements OnChanges , DoCheck {
23
+
24
+ @Input ( "mfData" ) private inputData :any [ ] = [ ] ;
25
+
26
+ private sortBy = "" ;
27
+ private sortOrder = "asc" ;
28
+
29
+ private rowsOnPage = 1000 ;
30
+ private activePage = 1 ;
31
+
32
+ private mustRecalculateData = false ;
33
+
34
+ public data : any [ ] ;
35
+
36
+ public onDataChange = new EventEmitter < DataEvent > ( ) ;
37
+ public onSortChange = new EventEmitter < SortEvent > ( ) ;
38
+ public onPageChange = new EventEmitter < PageEvent > ( ) ;
39
+
40
+ public getSort ( ) :SortEvent {
41
+ return { sortBy : this . sortBy , sortOrder : this . sortOrder } ;
42
+ }
43
+
44
+ public setSort ( sortBy :string , sortOrder :string ) :void {
45
+ if ( this . sortBy !== sortBy || this . sortOrder !== sortOrder ) {
46
+ this . sortBy = sortBy ;
47
+ this . sortOrder = sortOrder ;
48
+ this . mustRecalculateData = true ;
49
+ this . onSortChange . emit ( { sortBy : sortBy , sortOrder : sortOrder } ) ;
50
+ }
51
+ }
52
+
53
+ public getPage ( ) :PageEvent {
54
+ return { activePage : this . activePage , rowsOnPage : this . rowsOnPage , dataLength : this . inputData . length } ;
55
+ }
56
+
57
+ public setPage ( activePage :number , rowsOnPage :number ) :void {
58
+ if ( this . rowsOnPage !== rowsOnPage || this . activePage !== activePage ) {
59
+ this . rowsOnPage = rowsOnPage ;
60
+ this . activePage = activePage ;
61
+ this . mustRecalculateData = true ;
62
+ this . onPageChange . emit ( { activePage : this . activePage , rowsOnPage : this . rowsOnPage , dataLength : this . inputData . length } ) ;
63
+ }
64
+ }
65
+
66
+ public ngOnChanges ( changes :{ [ key :string ] :SimpleChange } ) :any {
67
+ if ( changes [ "inputData" ] ) {
68
+ this . onDataChange . emit ( { length : changes [ "inputData" ] . currentValue . length } ) ;
69
+ this . mustRecalculateData = true ;
70
+ }
71
+ }
72
+
73
+ public ngDoCheck ( ) :any {
74
+ if ( this . mustRecalculateData ) {
75
+ this . fillData ( ) ;
76
+ this . mustRecalculateData = false ;
77
+ }
78
+ }
79
+
80
+ private fillData ( ) :void {
81
+ this . activePage = this . activePage || 1 ;
82
+ this . rowsOnPage = this . rowsOnPage || 1000 ;
83
+
84
+ let offset = ( this . activePage - 1 ) * this . rowsOnPage ;
85
+ let data = this . inputData ;
86
+ data = _ . orderBy ( data , [ this . sortBy ] , [ this . sortOrder ] ) ;
87
+ data = _ . slice ( data , offset , offset + this . rowsOnPage ) ;
88
+ this . data = data ;
89
+ }
90
+ }
0 commit comments