Подтвердить что ты не робот

Как использовать флажок для булевых данных с ag-сетью

Я искал какое-то время и не видел настоящего примера.

Я использую ag-grid-реакцию, и я бы хотел, чтобы столбец содержал логическое выражение для представления булевого элемента с флажком и обновления объекта в строкеData при изменении.

Я знаю, что есть checkboxSelection, и я попытался использовать его, как то, что у меня ниже, но понял, что он имеет флажок, он не связан с данными и просто предназначен для выбора ячейки.

var columnDefs = [
        { headerName: 'Refunded', field: 'refunded', checkboxSelection: true,}
  ]

Итак, есть ли способ сделать то, что я ищу, с помощью ag-grid и ag-grid-реагировать?

4b9b3361

Ответ 1

Итак, в конце концов я немного получил то, что хотел, но несколько иначе, я использовал popupSelect и cellEditorParams со значениями: ['true', 'false']. Конечно, у меня нет фактического флажка, как я хотел, но он ведет себя достаточно хорошо для того, что мне нужно.

{
    headerName: 'Refunded', 
    field: 'refunded',
    cellEditor: 'popupSelect',
    cellEditorParams: {
        cellRenderer: RefundedCellRenderer,
        values: ['true', 'false']
    }
},

function RefundedCellRenderer(params) {
    return params.value;
}

Ответ 2

Вы должны использовать свойство cellRenderer

const columnDefs = [{ headerName: 'Refunded', 
    field: 'refunded', 
    editable:true,
    cellRenderer: params => {
        return `<input type='checkbox' ${params.value ? 'checked' : ''} />`;
    }
}];

Я застрял в одной и той же проблеме, это лучшее, что я мог придумать, но мне не удалось привязать значение к этому флажку.

Я установил для свойства ячейки значение true, теперь, если вы хотите изменить фактическое значение, вам нужно дважды щелкнуть ячейку и ввести true или false.

но это до тех пор, пока я пошел, и я решил помочь вам, я знаю, что это не на 100% решить все, но, по крайней мере, он решил часть представления данных.

сообщите, как вы делитесь своими ответами с нами.

Ответ 3

Код ниже помогает решить проблему. Недостатком является то, что обычные события в gridOptions не будут запущены (onCellEditingStarted, onCellEditingStopped, onCellValueChanged и т.д.).

var columnDefs = [...
           {headerName: "Label", field: "field",editable: true,
                cellRenderer: 'booleanCellRenderer',
                cellEditor:'booleanEditor'

            }
        ];
//register the components
$scope.gridOptions = {...
                components:{
                    booleanCellRenderer:BooleanCellRenderer,
                    booleanEditor:BooleanEditor
                }
            }; 

  function BooleanCellRenderer() {
  }

  BooleanCellRenderer.prototype.init = function (params) {
      this.eGui = document.createElement('span');
      if (params.value !== "" || params.value !== undefined || params.value !== null) {
          var checkedStatus = params.value ? "checked":"";
          var input = document.createElement('input');
          input.type="checkbox";
          input.checked=params.value;
          input.addEventListener('click', function (event) {
              params.value=!params.value;
              //checked input value has changed, perform your update here
              console.log("addEventListener params.value: "+ params.value);
          });
          this.eGui.innerHTML = '';
          this.eGui.appendChild( input );
      }
  };

  BooleanCellRenderer.prototype.getGui = function () {
      return this.eGui;
  };

  function BooleanEditor() {
  }

  BooleanEditor.prototype.init = function (params) {
      this.container = document.createElement('div');
      this.value=params.value;
      params.stopEditing();
  };
  BooleanEditor.prototype.getGui = function () {
      return this.container;
  };

  BooleanEditor.prototype.afterGuiAttached = function () {
  };

  BooleanEditor.prototype.getValue = function () {
      return this.value;
  };

  BooleanEditor.prototype.destroy = function () {
  };

  BooleanEditor.prototype.isPopup = function () {
      return true;
  };

Ответ 4

Как насчет этого? Это на Angular, а не на React, но вы могли бы понять:

        { headerName: 'Enabled', field: 'enabled', cellRendererFramework: CheckboxCellComponent },

И вот checkboxCellComponent:

@Component({
selector: 'checkbox-cell',
template: `<input type="checkbox" [checked]="params.value" (change)="onChange($event)">`,
styleUrls: ['./checkbox-cell.component.css']
}) 
export class CheckboxCellComponent implements AfterViewInit, 
ICellRendererAngularComp {

@ViewChild('.checkbox') checkbox: ElementRef;

public params: ICellRendererParams;

constructor() { }

agInit(params: ICellRendererParams): void {
  this.params = params;
}

public onChange(event) {
  this.params.data[this.params.colDef.field] = event.currentTarget.checked;
  }
}

Сообщите мне

Ответ 5

Мы можем использовать cellRenderer, чтобы показать флажок в сетке, который будет работать, когда вы также хотите редактировать поле. Сетка не будет обновлять значение флажка в gridoption - rowdata напрямую, пока вы не обновите узел с соответствующим полем в объекте узла, к которому может получить доступ объект params.

params.node.data.fieldName = params.value;

здесь fieldName - поле строки.

{
    headerName: "display name",
    field: "fieldName",
    cellRenderer: function(params) { 
        var input = document.createElement('input');
        input.type="checkbox";
        input.checked=params.value;
        input.addEventListener('click', function (event) {
            params.value=!params.value;
            params.node.data.fieldName = params.value;
        });
        return input;
    }
}

Ответ 6

В столбцеDefs добавьте столбец флажка. Не нужно устанавливать для свойства ячейки значение true

columnDefs: [ { headerName: '', field: 'checkbox', cellRendererFramework: CheckboxRenderer, width:30}, ...]

CheckboxRenderer

export class CheckboxRenderer extends React.Component{
    constructor(props) {
        super(props);
        this.state={
            value:props.value
        };
        this.handleCheckboxChange=this.handleCheckboxChange.bind(this);
    }

    handleCheckboxChange(event) {
        this.props.data.checkbox=!this.props.data.checkbox;
        this.setState({value: this.props.data.checkbox});
    }

    render() {
        return (    
        <Checkbox
            checked={this.state.value}
            onChange={this.handleCheckboxChange}></Checkbox>);
    }
}

Ответ 7

Массив значений строк не работает для меня, но работает массив из [true, false].

{
    headerName: 'Refunded',
    field: 'refunded',
    cellEditor: 'popupSelect',
    cellEditorParams: {
        cellRenderer: RefundedCellRenderer,
        values: [true, false]
    }
},

function RefundedCellRenderer(params) {
    return params.value;
}

Ответ 8

    import React, { Component } from 'react';


    export class CheckboxRenderer extends Component{
        constructor(props) {
            super(props);
            if(this.props.colDef.field==='noRestrictions'){
            this.state={


                value:true,
                disable:false


            };
        }
            else if(this.props.colDef.field==='doNotBuy')
            {
                this.state={


                    value:false,
                    disable:true


                }; 
            }
            this.handleCheckboxChange=this.handleCheckboxChange.bind(this);

        }

        handleCheckboxChange(event) {
             //this.props.data.checkbox=!this.props.data.checkbox; ={this.state.show}
             //this.setState({value: this.props.data.checkbox});
             if(this.state.value){this.setState({value: false});}
             else{this.setState({value: true});}
             alert(this.state.value);
             //check for the last row and check for the columnname and enable the other columns


        }

        render() {
            return (  


                 <input type='checkbox' checked={this.state.value} disabled={this.state.disable} onChange={this.handleCheckboxChange}/>





                );
        }
    }

    export default CheckboxRenderer;

import React, { Component } from 'react';
import './App.css';

import { AgGridReact } from 'ag-grid-react';
import CheckboxRenderer from './CheckboxRenderer';
import 'ag-grid/dist/styles/ag-grid.css';
import 'ag-grid/dist/styles/ag-theme-balham.css';

class App extends Component {
    constructor(props) {
        super(props);
        let enableOtherFields=false;
        this.state = {
            columnDefs: [
                {headerName: 'Make', field: 'make'},
                {headerName: 'noRestrictions', field: 'noRestrictions',
                cellRendererFramework: CheckboxRenderer,
                cellRendererParams:{checkedVal:true,disable:false},
                 onCellClicked: function (event) {
                   // event.node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal=!event.node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal;
                  // event.node.data.checkbox=!event.data.checkbox;   
                  let currentNode=event.node.id;
                   event.api.forEachNode((node) => {

                         if(node.id===currentNode)
                         {
                             node.data.checkbox=!node.data.checkbox;

                          }
                           //if(!node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal){ // checkbox is unchecked
                              if(node.data.checkbox===false && node.data.checkbox!=='undefined'){
                              enableOtherFields=true;


                           }
                           else
                           {
                              enableOtherFields=false;

                           }

                        //alert(node.id);
                        //alert(event.colDef.cellRendererParams.checkedVal);

                       }); alert("enable other fields:"+enableOtherFields);


                 }

                },
                {headerName:'doNotBuy',field:'doNotBuy',
                cellRendererFramework: CheckboxRenderer,
                cellRendererParams:{checkedVal:false,disable:true}

                },

                {headerName: 'Price', field: 'price', editable: true}

            ],
            rowData: [
                {make: "Toyota",noRestrictions:true,doNotBuy:false,  price: 35000},
                {make: "Ford", noRestrictions:true,doNotBuy:false,price: 32000},
                {make: "Porsche", noRestrictions:true,doNotBuy:false, price: 72000}
            ]
        };
    }


    componentDidMount() {

    }

    render() {
        return (
            <div
                className="ag-theme-balham"
                style={{height: '200px', width: '800px'}}
            >
                <AgGridReact
                    enableSorting={true}
                    enableFilter={true}
                    //pagination={true}
                    columnDefs={this.state.columnDefs}
                    rowData={this.state.rowData}>
                </AgGridReact>
            </div>
        );
    }
}

export default App;

Ответ 9

Булевы данные в настоящей части:

    function booleanCellRenderer(params) { 
        var valueCleaned = params.value;
        if (valueCleaned === 'T') {
            return '<input type="checkbox" checked/>';
        } else if (valueCleaned === 'F') {
            return '<input type="checkbox" unchecked/>';
        } else if (params.value !== null && params.value !== undefined) {
            return params.value.toString();
        } else {
            return null;
        }
    }

    var gridOptions = { 
        ...
        components: {
            booleanCellRenderer: booleanCellRenderer,
        }
    };

    gridOptions.api.setColumnDefs(
      colDefs.concat(JSON.parse('[{"headerName":"Name","field":"Field", 
        "cellRenderer": "booleanCellRenderer"}]')));

Ответ 10

Вы можете использовать логическое (истина или ложь)

Я пытаюсь это, и это работает:

var columnDefs = [
  {
    headerName: 'Refunded', 
    field: 'refunded',
    editable: true,
    cellEditor: 'booleanEditor',
    cellRenderer: booleanCellRenderer
  },
];

Редактор флажков функций

function getBooleanEditor() {
    // function to act as a class
    function BooleanEditor() {}

    // gets called once before the renderer is used
    BooleanEditor.prototype.init = function(params) {
        // create the cell
        var value = params.value;

        this.eInput = document.createElement('input');
        this.eInput.type = 'checkbox'; 
        this.eInput.checked = value;
        this.eInput.value = value;
    };

    // gets called once when grid ready to insert the element
    BooleanEditor.prototype.getGui = function() {
        return this.eInput;
    };

    // focus and select can be done after the gui is attached
    BooleanEditor.prototype.afterGuiAttached = function() {
        this.eInput.focus();
        this.eInput.select();
    };

    // returns the new value after editing
    BooleanEditor.prototype.getValue = function() {
        return this.eInput.checked;
    };

    // any cleanup we need to be done here
    BooleanEditor.prototype.destroy = function() {
        // but this example is simple, no cleanup, we could
        // even leave this method out as it optional
    };

    // if true, then this editor will appear in a popup
    BooleanEditor.prototype.isPopup = function() {
        // and we could leave this method out also, false is the default
        return false;
    };

    return BooleanEditor;
}

И тогда функция booleanCellRenderer

function booleanCellRenderer(params) {
    var value = params.value ? 'checked' : 'unchecked';

    return '<input disabled type="checkbox" '+ value +'/>';
}

Сообщите сетке, какие столбцы и какие данные использовать

var gridOptions = {
    columnDefs: columnDefs,
    pagination: true,
    defaultColDef: {
        filter: true,
        resizable: true,
    },
    onGridReady: function(params) {
        params.api.sizeColumnsToFit();
    },
    onCellValueChanged: function(event) {
        if (event.newValue != event.oldValue) { 
            // do stuff
            // such hit your API update
            event.data.refunded = event.newValue; // Update value of field refunded
        }
    },
    components:{
        booleanCellRenderer: booleanCellRenderer,
        booleanEditor: getBooleanEditor()
    }
};

Настройте сетку после завершения загрузки страницы

document.addEventListener('DOMContentLoaded', function() {
    var gridDiv = document.querySelector('#myGrid');
    // create the grid passing in the div to use together with the columns & data we want to use
    new agGrid.Grid(gridDiv, gridOptions);

    fetch('$urlGetData').then(function(response) {
        return response.json();
    }).then(function(data) {
        gridOptions.api.setRowData(data);
    })
});