agGrid Row 추가 / 삭제

▶︎ agGrid 그리드에서 Row를 신규로 추가하거나 체크박스 체크 후 Row를 삭제하는 방법이다. 먼저 updateRowData함수를 이용해서 새로운 Row를 추가하는 방법이다. 추가할 Row 객체를 포함하여 객체 배열을 넘겨서 하나 이상의 Row를 추가할 수 있다.

let idx = 0;
function addRow() {
        idx++;
        let newRow = { make: "Toyota"+idx, model: "Celica"+idx, price: 3500+idx*10 };
        // 배열데이터 추가 가능, 즉, 여러개의 Row를 한꺼번에 Add 가능하다.
        gridOptions.api.updateRowData({add:[newRow]});
}

▶︎ 체크 박스로 Row를 선택 후 삭제하는 방법이대.

function removeRow() {
        let selectedData = gridOptions.api.getSelectedRows();
        gridOptions.api.updateRowData({remove: selectedData});
}
agGrid Row 추가/삭제

▶︎ 전체 소스

<!DOCTYPE html>

<html lang="ko">
<head>
    <meta charset="utf-8">
    <title>agGrid - Row 추가/삭제</title>
    <script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.js"></script>

<script type="text/javascript">
    let idx = 0;
    const columnDefs = [
        {headerCheckboxSelection: true, checkboxSelection: true, maxWidth:50, filter:false, sortable:false, cellClass: 'stringType'},
        { field:"make", width:100},
        { field:"model", width:100 },
        { field:"price", width:100}
    ];

    // specify the data
    const rowData = [
        { make: "Toyota", model: "Celica", price: 350 },
        { make: "현대", model: "싼타페", price: 12000 },
        { make: "Ford", model: "Mondeo", price: 32000 },
        { make: "쌍용", model: "뭐더라", price: 7000 },
        { make: "Porsche", model: "Boxter", price: 72000 }
    ];

    // let the grid know which columns and what data to use
    const gridOptions = {
        rowSelection: 'multiple',// 'single' - default
        columnDefs: columnDefs,
        rowData: rowData
    };

    // setup the grid after the page has finished loading
    document.addEventListener('DOMContentLoaded', () => {
        const gridDiv = document.querySelector('#myGrid');
        new agGrid.Grid(gridDiv, gridOptions);
    });

    function addRow() {
        idx++;
        let newRow = { make: "Toyota"+idx, model: "Celica"+idx, price: 3500+idx*10 };
        // 배열데이터 추가 가능, 즉, 여러개의 Row를 한꺼번에 Add 가능하다.
        gridOptions.api.updateRowData({add:[newRow]});
    }

    function removeRow() {
        let selectedData = gridOptions.api.getSelectedRows();
        gridOptions.api.updateRowData({remove: selectedData});
    }
</script>
</head>
<body>


<div id="myGrid" style="height: 250px; width:500px;" class="ag-theme-balham"></div>
<button onclick="addRow()">Add</button>
<button onclick="removeRow()">Remove</button>

</body>
</html>