AG Grid: Detect change and give alert when user is trying to edit other row without saving the first

1.1k Views Asked by At

We have new project in Angular 8 where we are using AG Grid, Now user wants a validation to fire if someone edits one row and without saving it moves to another record/Row. it should say Save your data first.

I have tried same on onRowChange functionality, but user don't want validation to fire on click they only want validation to fire when they edit something.

below is the sample code of what I have done, but this is not fully achieving the purpose,Can someone help me on this? I have tried onValueChange() as well, it didn't work.

Code:

    onRowClick(event: any) {
        if (this.cellChangeCount === 0) {
          this.UnsavedNodeIndex = event.node.rowIndex;
          this.UnsavedNodeID = event.data.ID;
        }
        

        this.commonAgGrid.commonAgGridfunc(event, this.gridApi, this.cellChangeCount, this.UnsavedNodeIndex, this.newRowClicked,
          this.UnsavedNodeID, this.colName);
          this.cellChangeCount++;
      }

  commonAgGridfunc(event: any, gridApi, cellChangeCount, UnsavedNodeIndex, newRowClicked, UnsavedNodeID, colName) {
    
    cellChangeCount = cellChangeCount == 0 ? 0 : cellChangeCount;
    cellChangeCount = newRowClicked == true ? 0 : cellChangeCount;
    if (cellChangeCount !== 0 && (UnsavedNodeID != event.data.ID) && !newRowClicked) {

      if (typeof UnsavedNodeID != "undefined") {
        this.alertService.info("Save data first.");
        setTimeout(() => this.alertService.clear(), 2000);
        this.onBtStartEditing(gridApi, UnsavedNodeIndex, colName);
      }
    }
    if (newRowClicked == true && (UnsavedNodeID != event.data.ID)) {
      gridApi.stopEditing();
      gridApi.setFocusedCell(0, colName);
      gridApi.startEditingCell({
        rowIndex: 0,
        colKey: colName,
      });
      gridApi.forEachNode(node => node.rowIndex == 0 ? node.setSelected(true) : node.setSelected(false))
    }

  }
1

There are 1 best solutions below

1
On

You can try using onCellvalueChanged() instead of rowClick.

 onCellvalueChanged(event: any) {
    if (this.cellChangeCount === 0) {
      this.UnsavedNodeIndex = event.node.rowIndex;
      this.UnsavedNodeID = event.data.ID;
    }