Получить все отредактированные строки из Angular гладкой сетки при нажатии кнопки «Сохранить все» - PullRequest
2 голосов
/ 28 мая 2020

У меня есть приложение Ioni c, в котором я использую встроенное редактирование, используя Angular slick-grid для редактирования пояса. В моем случае пользователь внесет все необходимые изменения и, наконец, на кнопке «сохранить все» нажмите все отредактированные данные должны быть обновлены в БД. Я хочу знать, есть ли способ извлечения отредактированных записей из сетки / набора данных по умолчанию вместо сохранения внешней переменной для хранения идентификаторов отредактированных записей.

//I use this method to update the dataset.    
onCellChanged(e, args) {
        this.angularGrid.gridService.updateDataGridItemById(args.item['id'], args.item);
    }

1 Ответ

1 голос
/ 28 мая 2020

Вы можете использовать очередь команд редактирования, чтобы узнать, какие элементы были изменены. Эта очередь полезна для выполнения операции «Отменить» при возникновении какой-либо ошибки или когда вы просто хотите отменить. Очередь отслеживает все индексы строк / ячеек элементов и их значения до / после того, как это было изменено, вы можете получить все элементы оттуда, и после того, как вы «Сохранить все», вы можете просто сбросить эту очередь.

export class MyComponent {
  private angularGrid: AngularGridInstance;
  private dataViewObj: any;
  private gridObj: any;
  private editQueue = [];

  angularGridReady(angularGrid: AngularGridInstance) {
    this.angularGrid = angularGrid;
    this.gridObj = angularGrid.slickGrid;
    this.dataViewObj = angularGrid.dataView;
  }

  prepareGrid() {
    this.columnDefinitions = [ /*...*/ ];

    this.gridOptions = {
      autoEdit: true,
      editable: true,
      enableCellNavigation: true,
      editCommandHandler: (item, column, editCommand) => {
        this.editQueue.push(editCommand); // <-- last edit command
        editCommand.execute();
      },
    };
  }

  handleOnErrorCallback(error, gridObj) {
     // undo last edit in the grid
     const lastEdit = this.editQueue.pop();
     if (lastEdit && lastEdit.command) {
        lastEdit.command.undo();
        gridObj.gotoCell(lastEdit.command.row, lastEdit.command.cell, false);
     }
     return false;
  }

  saveAll() {
     // for example, to get the last Edit, you could type get it this way
     // const lastEdit = this.editQueue[this.editQueue.length - 1];
     // const lastEditField = lastEdit && lastEdit.column && lastEdit.column.field;

     const editItems = [];

     // in your case, you would want to loop through the entire queue
     this.editQueue.forEach((editObj) => {
       const previousValue = editObj.prevSerializedValue;
       const newValue = editObj.serializedValue;
       const rowIndex = editObj.row; // from the row index, you can get the item
       const item = this.angularGrid.dataView.getItem(rowIndex);

       // do what you want with the value or item
       editItems.push(item);
     });

     // call your save all method
     // this.saveInDb(editItems);

     // don't forget to reset your edit queue to restart with a new batch of edits
     this.editQueue = [];     
  }
}

На самом деле, написав это, я просто увидел, что может быть проще просто получить массив элементов непосредственно из editCommandHandler

export class MyComponent {
  private editItems = [];

  prepareGrid() {
    this.columnDefinitions = [ /*...*/ ];

    this.gridOptions = {
      autoEdit: true,
      editable: true,
      enableCellNavigation: true,
      editCommandHandler: (item, column, editCommand) => {
        this.editItems.push(item);
        this.editQueue.push(editCommand); // <-- last edit command
        editCommand.execute();
      },
    };
  }

  saveAll() {
    // call your save all method
    // this.saveInDb(editItems);

    // don't forget to reset your edit queue to restart with a new batch of edits
    this.editQueue = [];   
    this.editItems = [];
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...