티스토리 뷰

UI(Front-End)/그리드

AG-GRID 기본 예제

까오기 까오기 2019. 1. 30. 14:00

1. 기본 예제 코드

AG-GRID를 이용해서 화면에 데이터를 보여주는 예제입니다. 

Athlete, Age 칼럼은 좌측에 고정을 시켰습니다. 

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>AG GRID 예제</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <!--@@@ 주요 라이브러리 @@@-->  
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
  <script src="https://unpkg.com/ag-grid/dist/ag-grid.min.js"></script>
  <script src="/assets/js/agGridUtil.js"></script>
  <!--### 주요 라이브러리 ###-->  
</head>
<body>
<div class="container">
    <h2>AG GRID 기본 예제</h2>
    <div class="grid-wrapper">
        <div style="width: 100%; height:580px" id="myGrid" class="ag-grid-div ag-theme-balham ag-basic"></div>
    </div>
</div>
<script>
 var MainGrid = function(){
    var _this = this;
    /* grid 영역 정의 */
    this.gridDiv = "myGrid";
    /* grid 칼럼 정의 */
    this.getColumnDefs = function(){
     var columnDefs = [
         {headerName:"Athlete", field: "athlete", width: 150, minWidth:120, pinned:'left', suppressSizeToFit: true, suppressMenu: true, sort: 'asc'},
         {headerName:"Age", field: "age", width: 90, minWidth: 50, maxWidth: 100, pinned:'left'suppressMenu: true, suppressSorting : true},
        {headerName:"Country", field: "country", width: 120},
         {headerName:"Year", field: "year", width: 90},
         {headerName:"Date", field: "date", width: 110},
         {headerName:"Sport", field: "sport", width: 110},
         {headerName:"Gold Medal", field: "gold", width: 100},
         {headerName:"Silver Medal", field: "silver", width: 100},
         {headerName:"Bronze Medal", field: "bronze", width: 100},
         {headerName:"Total", field: "total", width: 100}
    ];
        var gridOpt = CommonGrid.getDefaultGridOpt(columnDefs);
        return gridOpt;
    };
    /* grid 옵션 가져오기 */
    this.gridOpts = null
    /* grid 실행 */
    this.makeGrid = function(rowData){
        _this.gridOpts = _this.getColumnDefs();
        CommonGrid.makeGridCommon(_this.gridDiv, _this.gridOpts, rowData)
    };
}
var mainGrid = new MainGrid();
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded'function() {
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET''./olympicWinnersSmall.json');
    httpRequest.send();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4 && httpRequest.status === 200) {
            var httpResult = JSON.parse(httpRequest.responseText);
            mainGrid.makeGrid(httpResult);
        }
    };
});  
</script>
 
</body>
</html>
cs

UTIL JAVASCRIPT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/**
* AG-GRID COMMON UTILS
* @author kkaok, kkaok.pe.kr@gmail.com
*/
/**
 * currency 표현. 세자리 마다 콤마
 */
Number.prototype.format = function(n, x) {
    var re = '\\d(?=(\\d{' + (x || 3+ '})+' + (n > 0 ? '\\.' : '$'+ ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};
 
/**
 * NameValue Object
 */
var NameValue = function (pname, pvalue){
    this.name = pname;
    this.value = pvalue;
}
/**
 * cellRenderer 등에서 사용하기 위한 것으로 
 * 배열로 코드를 받아서 node의 값과 일치하는 value를 반환한다. 
 */
var getCodeValue = function(codes, nodeData){
    if(!codes) return " - ";
    for(var i=0;i<codes.length;i++){
        if(nodeData.value == codes[i].name){
            return codes[i].value;
        }
    }
    return " - ";
}
 
/**
 * 콤보박스 처리 
 * 객체에서 key값 추출하는 함수
 * var data = {
 *     headerName : "월",
 *     field : "mon",
 *     width : 100,
 *     editable : true,
 *     cellEditor : 'agSelectCellEditor',
 *     cellStyle : {
 *         "textAlign" : "center"
 *     },
 *     cellRenderer : CommonGrid.convertLeadTime,
 *     cellEditorParams : {
 *         values : extractValues(CommonCode.leadTimeCodes())
 *     },
 *     valueFormatter : function(params) {
 *         return lookupValue(CommonCode.leadTimeCodes(), params.value);
 *     },
 *     valueParser : function(params) {
 *         return lookupKey(CommonCode.leadTimeCodes(), params.newValue);
 *     }
 * }
 */
function extractValues(mappings) {
    var params = new Array();
    for (var i = 0; i< mappings.length;i++) {
        params.push(mappings[i].name);
    }
    return params;
}
 
/**
 * 객체에서 key로 value을 반환하는 함수, 콤보박스에서 사용
 */
function lookupValue(mappings, key) {
    for (var i = 0; i< mappings.length;i++) {
        if (mappings[i].name == key) {
            return mappings[i].value;
        }    
    }
    return "";
}
 
/**
 * 객체에서 vaue로 key를 반환하는 함수, 콤보박스에서 사용
 */
function lookupKey(mappings, name) {
    for (var i = 0; i< mappings.length;i++) {
        if (mappings[i].value == name) {
            return mappings[i].name;
        }    
    }
    return "";
}
 
/**
 * Date Picker 사용법 
 * 1. 칼럼 정의 시 editable : true, cellEditor : 'datePicker' 추가 
 * 2. 칼럼옵션에 컴포넌트 추가 
 * gridOpt.components = {
 *  datePicker: getDatePicker('yy-mm-dd') // date format 지정시 포맷 전달 
 *  datePicker: getDatePicker()  // 기본은 yymmdd 8자리로 됨 
 * };
 */
function getDatePicker(paramFmt) {
    var _this = this;
    _this.fmt = "yymmdd";
    if(paramFmt){
        _this.fmt = paramFmt;
    }
    // function to act as a class
    function Datepicker() {}
 
    // gets called once before the renderer is used
    Datepicker.prototype.init = function(params) {
        // create the cell
        this.eInput = document.createElement('input');
        this.eInput.value = params.value;
 
        // https://jqueryui.com/datepicker/
        $(this.eInput).datepicker({
            dateFormat: _this.fmt
        });
    };
 
    // gets called once when grid ready to insert the element
    Datepicker.prototype.getGui = function() {
        return this.eInput;
    };
 
    // focus and select can be done after the gui is attached
    Datepicker.prototype.afterGuiAttached = function() {
        this.eInput.focus();
        this.eInput.select();
    };
 
    // returns the new value after editing
    Datepicker.prototype.getValue = function() {
        return this.eInput.value;
    };
 
    // any cleanup we need to be done here
    Datepicker.prototype.destroy = function() {
        // but this example is simple, no cleanup, we could
        // even leave this method out as it's optional
    };
 
    // if true, then this editor will appear in a popup
    Datepicker.prototype.isPopup = function() {
        // and we could leave this method out also, false is the default
        return false;
    };
 
    return Datepicker;
}
/**
 * 공통 그리드 util
 */
var CommonGrid = {
        defaultBlank : " - "
        // csv 파일 export    
        ,onBtExport : function(title, gridOpts){
            var params = {
                    skipHeader: false,
                    skipFooters: false,
                    columnGroups: true,
                    skipGroups: false,
                    skipPinnedTop: false,
                    skipPinnedBottom: false,
                    allColumns: true,
                    onlySelected: false,
                    fileName: title + moment().format("YYYYMMDDHHmmss")+ '.csv'
            };
            gridOpts.api.exportDataAsCsv(params);
        }
        // 칼럼정의 값으로 기본 grid option을 생성한다.      
        ,getDefaultGridOpt : function(pColumnDefs) {
            return this.getDefaultGridOptResize(pColumnDefs, true);
        }
        // 칼럼정의 값으로 기본 grid option을 생성한다. 리사이즈 안함.       
        ,getDefaultGridOptNoResize : function(pColumnDefs) {
            return this.getDefaultGridOptResize(pColumnDefs, false);
        }
        // 칼럼정의 값으로 기본 grid option을 생성한다.      
        ,getDefaultGridOptResize : function(pColumnDefs,autosize) {
            return {
                columnDefs: pColumnDefs,
                rowSelection: 'single'/* 'single' or 'multiple',*/
                enableColResize: true,
                enableSorting: true,
                enableFilter: true,
                enableRangeSelection: true,
                suppressRowClickSelection: false,
                animateRows: true,
                suppressHorizontalScroll: false,
                localeText: {noRowsToShow: '조회 결과가 없습니다.'},
                getRowStyle: function (param) {
                    if (param.node.rowPinned) {
                        return {'font-weight''bold', background: '#dddddd'};
                    }
                    return {'text-align''center'};
                },
                getRowHeight: function(param) {
                    if (param.node.rowPinned) {
                        return 30;
                    }
                    return 30;
                },
                // 리사이즈 
                onGridReady: function(params) {
                    params.api.sizeColumnsToFit();
                },
                // 창 크기 변경 되었을 때 이벤트 
                onGridSizeChanged: function(params) {
                    params.api.sizeColumnsToFit();
                },
                debug: false
            };
        }
        // 그리드 값 넣기 
        ,makeGridCommon : function (gridDiv, pGridOpts, rowData){
            $('#'+gridDiv).children().remove();
            var eGridDiv = document.querySelector('#'+gridDiv);
            new agGrid.Grid(eGridDiv, pGridOpts);
            pGridOpts.api.setRowData(rowData);
        }
        ,convertTime : function (param){
            if(!param.value) {
                return this.defaultBlank;
            }else {
                return moment(param.value, "YYYYMMDDHHmmss").format("HH:mm");
            }
        }
        ,convertDate : function(param) { // 8자리 문자열을 날짜로 변환
            if(!param.value) {
                return this.defaultBlank;
            }else{
                if(param.value.length ==8) {
                    return moment(param.value, "YYYYMMDD").format("YYYY-MM-DD");
                }else{
                    return param.value;
                }
            }        
        }
        ,convertTimestamp : function(param) { // 8자리 문자열을 날짜로 변환
            if(!param.value) {
                return this.defaultBlank;
            }else {
                return moment(param.value, "YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss");
            }        
        }
        ,formatDate : function(param) { // long 값을 날짜로 변환
            if(!param.value) {
                return this.defaultBlank;
            }else {
                return moment(parseInt(param.value)).format("YYYY-MM-DD");
            }        
        }
        ,formatTimestamp : function(param) { // long 값을 날짜로 변환
            if(!param.value) {
                return this.defaultBlank;
            }else {
                return moment(parseInt(param.value)).format("YYYY-MM-DD HH:mm:ss");
            }        
        }
        ,numberOnly : function(param){ 
            if(!param.value || param.value ==''return '';
            if (typeof param.value === 'string') {
                return param.value.replace(/[^0-9\.]+/g, '');
            }
            return CommonGrid.formatCurrency(param);
        }
        ,formatCurrency : function (param){
            if(!param.value && param.value != "0") {
                return this.defaultBlank;
            }    
            return parseInt(param.value).format();
        }
        ,formatNumber : function(param){
            if(!param.value && param.value != "0") {
                return this.defaultBlank;
            }    
            return numberFormatPoint2Digits(param.value);
        }
        ,convertCommon : function(codes, param){
            if(!codes) return " - ";
            for(var i=0;i<codes.length;i++){
                if(param.value == codes[i].name){
                    return codes[i].value;
                }
            }
            return this.defaultBlank;
        }
        ,getCode : function(codes, value){
            for(var i=0;i<codes.length;i++){
                if(value == codes[i].value){
                    return codes[i].name;
                }
            }
            return "";
        }
        ,checkMobile : function(gridOpts){
            // 모바일 브라우저 가로크기 체크
            if (document.body.clientWidth < 800) {
                if(gridOpts){
                    gridOpts.columnDefs.forEach(function(el) {
                        el.pinned = null;
                        if(el.children){
                            el.children.forEach(function(subEl) {
                                subEl.pinned = null;
                            });
                        }
                    });
                }
            }
        }
        ,makeTopGrid : function(gridMainOpts, rowData, params){
            var colsSum = [];
            gridMainOpts.columnDefs.forEach(function(coldefs, index) {
                if(coldefs.children){
                    coldefs.children.forEach(function(child, index) {
                        if(child.isSum && child.isSum == true){
                            var temp = {};
                            temp[child.field] = 0;
                            temp["field"= child.field;
                            colsSum.push(temp);
                        }
                    });
                }else{
                    if(coldefs.isSum && coldefs.isSum == true){
                        var temp = {};
                        temp[coldefs.field] = 0;
                        temp["field"= coldefs.field;
                        colsSum.push(temp);
                    }
                }
            });
            rowData.forEach(function(rowvalue, index) {
                colsSum.forEach(function(value, index) {
                     if(rowvalue[value.field] && !rowvalue[value.field].isNaN)
                         value[value.field] += rowvalue[value.field];
                });
            });
             var resultSum = {}
             colsSum.forEach(function(cValue, index) {
                 resultSum[cValue.field] = cValue[cValue.field];
 
            });
             if(params && params.length>0){
                 params.forEach(function(value, index) {
                     resultSum[value.field] = value.value;
                });
             }
             resultSum['top'= true;
            var resultArray = [];
            resultArray[0= resultSum;
            gridMainOpts.api.setPinnedTopRowData(resultArray);
        }
    }
cs

Json data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[
    {
        "athlete": "Michael Phelps",
        "age": 23,
        "country": "United States",
        "year": 2008,
        "date": "24/08/2008",
        "sport": "Swimming",
        "gold": 8,
        "silver": 0,
        "bronze": 0,
        "total": 8
    },
    {
        "athlete": "Michael Phelps",
        "age": 19,
        "country": "United States",
        "year": 2004,
        "date": "29/08/2004",
        "sport": "Swimming",
        "gold": 6,
        "silver": 0,
        "bronze": 2,
        "total": 8
    },
    {
        "athlete": "Michael Phelps",
        "age": 27,
        "country": "United States",
        "year": 2012,
        "date": "12/08/2012",
        "sport": "Swimming",
        "gold": 4,
        "silver": 2,
        "bronze": 0,
        "total": 6
    }
]
cs


파일 첨부 

simpleExample.zip





'UI(Front-End) > 그리드' 카테고리의 다른 글

AG-GRID Data 선택 이벤트 처리 예제  (0) 2019.01.30
AG-GRID cellRenderer 예제  (4) 2019.01.30
AG-GRID 기본 예제  (0) 2019.01.30
AG-GRID GRID OPTIONS 정의  (2) 2019.01.30
AG-GRID 칼럼 정의  (0) 2019.01.30
AG-GRID 설치 및 기본구조  (2) 2019.01.30
댓글
댓글쓰기 폼