반응형

AG Grid에서 Row를 추가하고 삭제하는 예제에 대해서 이번 글을 시작한다.


AG Grid Row 추가

AG Grid 내부에서 Row를 신규로 추가하는 방법이다.

이 방법은 updateRowData 함수를 사용하여 Row를 추가할 수 있다.

const GRID = {
	addRow: function () { // addRow 시 빈줄 추가 (2023-01-16, ANDUM)
    			let _this = this;
                
                const newRow = {};
                _this.gridOptions.api.updateRowData({add:[newRow]});
	}
}

 

위와 같이, newRow를 생성하여 gridOptions.api.updateRowData({add:[newRow]}) 로 Row를 추가할 수 있다.

 

결과

 

위와 같이, 버튼을 누르면 AG Grid의 맨 위의 Row가 1칸 생성된다.


AG Grid Row 삭제

AG Grid 내부에서 Row를 삭제하는 방법이다.

이 방법도 위와 같이 updateRowData 함수를 사용하여 Row를 삭제할 수 있다.

const GRID = {
	deleteRow: function(){
                let _this = this;
                const selectedRows = _this.gridOptions.api.getSelectedRows();

                if(selectedRows.length < 1){
                    alert('선택된 항목이 없습니다.')
                    return false;
                }
                
                _this.gridOptions.api.updateRowData({ remove: selectedRows });

	}
}

 

결과

 

위와 같이 체크 후 삭제 버튼을 누르면, 아래와 같이 선택된 Row가 삭제 된다.

 


참고사항

위의 함수인 updateRowData를 사용해도 되고, applyTransaction 함수를 사용해도 된다.

applyTransaction 함수의 경우 대규모 데이터를 수정했을 경우나 생성했을 경우에 효율적이라고 공식 문서에 나와 있다.


전체 소스 코드

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>

<script>
	let idx = 0;
        const GRID = {
            agGrid: null
            , gridOptions: null
            , init: function(){
                this.initGrid();
            }
            , initGrid: function(){
                let _this = this;
                _this.gridOptions = {
                    columnDefs: [
                        {
                            minWidth: 50,
                            headerCheckboxSelection: true,
                            checkboxSelection: true,
                        },
                        {headerName:"USERID", field: "USERID", width: 150, minWidth:120, suppressSizeToFit: true, suppressMenu: true, sort: 'asc'},
						{headerName:"NMLAST", field: "NMLAST", width: 150, minWidth:120, suppressSizeToFit: true, suppressMenu: true, sort: 'asc'},
                    ],
                    defaultColDef: {
                        flex: 1,
                        minWidth: 200,
                        sortable: true,
                        resizable: true,
                        editable: true,
                        floatingFilter: true,
                    },
                    rowSelection: 'multiple',
                    editType: 'fullRow',
                    onRowValueChanged: _this.onRowValueChanged,
                    onSelectionChanged: function(){

                    }
                };

                document.addEventListener('DOMContentLoaded', () => {
                    const gridDiv = document.querySelector('#myGrid');
                    _this.agGrid = new agGrid.Grid(gridDiv, _this.gridOptions);
                    fetch("/common/search/json/data2.json")
                        .then((response) => response.json())
                        .then((data) => _this.gridOptions.api.setRowData(data.data));
                });
            }
            , onRowValueChanged: function(event){
                let data = event.data;
                console.log("edit date ==> ", data);

                fetch("/wms/system/json/saveSUI012.json", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(data),
                }).then((response) => {
                    console.log(response);
                    alert("수정되었습니다.");
                });
            }
            , addRow: function () { // addRow 시 빈줄 추가 (2023-01-16, ANDUM)
                let _this = this;
                
                const newRow = {};
                
                _this.gridOptions.api.updateRowData({add:[newRow]});
            }
            , deleteRow: function(){
                let _this = this;
                const selectedRows = _this.gridOptions.api.getSelectedRows();

                if(selectedRows.length < 1){
                    alert('선택된 항목이 없습니다.')
                    return false;
                }
                
                _this.gridOptions.api.updateRowData({ remove: selectedRows });

            }
            , searchList: function() {
            	let _this = this;
            	let param = inputList.setRangeParam("searchArea");
            	
            	fetch("/common/search/json/data2.json", {
            		method : 'POST',
            		headers: {
    					'Content-Type': 'application/json',
            		},
            		body: JSON.stringify(param.map),
            	})
                .then((response) => response.json())
                .then((data) => GRID.gridOptions.api.setRowData(data.data));
            }
        }

        GRID.init();
        window.GRID = GRID;
        
        /* BUTTON CLICK EVENT */
    	function commonBtnClick(btnName){
    		if(btnName == "Search"){
    			searchList();
    		}else if(btnName == "Save"){
    			GRID.onRowValueChanged(this);
    		}else if(btnName == "Add"){
				GRID.addRow();
    		}else if(btnName == "Delete"){
				GRID.deleteRow();
    		}
    	}
        
        function searchList() {
        	GRID.searchList();
        }
        
    </script>
</head>
<body>
<div style="width: 100%; height: 580px" id="myGrid" class="ag-grid-div ag-theme-balham ag-basic"></div>
</body>
</html>

 

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기