如何使用带有 ag-grid 的布尔数据的复选框

How to use a checkbox for a boolean data with ag-grid

我已经搜索了一段时间,还没有看到任何真实的例子。

我正在使用 ag-grid-react,我想要一个包含布尔值的列来表示带有复选框的布尔值,并在更改时更新 rowData 中的对象。

我知道有 checkboxSelection 并且我尝试像下面那样使用它,但意识到虽然它是一个复选框,但它没有链接到数据并且仅用于选择一个单元格。

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

那么有没有办法用 ag-grid 和 ag-grid-react 来做我正在寻找的东西?

你应该使用 cellRenderer 属性

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

我遇到了同样的问题,这是我能想到的最好的办法,但我无法将值绑定到此复选框。

我将单元格 属性 editable 设置为 true ,现在如果您想更改实际值,您必须双击该单元格并输入 true 或 false。

但就我所及,我决定帮助你,我知道它不能 100% 解决所有问题,但至少它解决了数据表示部分。

如果您知道如何与我们分享您的答案。

所以最后我有点得到了我想要的东西,但以一种稍微不同的方式,我使用了 popupSelect 和 cellEditorParams 的值:['true','false']。当然,我没有我想要的实际复选框,但它的表现足以满足我的需要

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

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

在 columnDefs 中,添加一个复选框列。不需要将单元格 属性 editable 设置为 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>);
    }
}

这个呢?它在 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;
    }
}

告诉我

字符串值数组对我不起作用,但 [true,false] 数组有效。

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

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

下面的代码有助于解决这个问题。缺点是不会触发 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;
  };
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;

当前部分的布尔数据:

    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"}]')));

我们可以使用 cellRenderer 在网格中显示复选框,当您还想编辑该字段时,这将起作用。 Grid 不会直接更新 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;
    }
}

您可以使用布尔值(真或假)

我尝试了这个并且成功了:

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's 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);
    })
});

这是一个对我有用的解决方案。必须遵守箭头功能以解决上下文问题。

组件:

import React from "react";

class AgGridCheckbox extends React.Component {

  state = {isChecked: false};

  componentDidMount() {
    let boolValue = this.props.value.toString() === "true";
    this.setState({isChecked: boolValue});
  }

  onChanged = () => {
    const checked = !this.state.isChecked;
    this.setState({isChecked: checked});
    this.props.setValue(checked);
  };

  render() {
    return (
      <div>
        <input type={"checkbox"} checked={this.state.isChecked} onChange={this.onChanged}/>
      </div>
    );
  }
}

export default AgGridCheckbox;

columnDefs 数组中的列定义对象:

{
  headerName: "yourHeaderName",
  field: "yourPropertyNameInsideDataObject",
  cellRendererFramework: AgGridCheckbox
}

JSX 调用 ag-grid:

<div
    className="ag-theme-balham"
  >
    <AgGridReact
      defaultColDef={defaultColDefs}
      columnDefs={columnDefs}
      rowData={data}
    />
</div>

React具体解决方案

当使用带有 React Hooks 的 React (16.x) 功能组件时,可以轻松编写您的 cellRenderer。这是 pnunezcalzado 之前发布的等效函数。

单元格渲染器的 React 组件

function AgGridCheckbox (props) {
  const boolValue = props.value && props.value.toString() === 'true';
  const [isChecked, setIsChecked] = useState(boolValue);
  const onChanged = () => {
    props.setValue(!isChecked);
    setIsChecked(!isChecked);
  };
  return (
    <div>
      <input type="checkbox" checked={isChecked} onChange={onChanged} />
    </div>
  );
}

在您的网格中使用它

调整列定义 (ColDef) 以使用此单元格渲染器。

{
  headerName: 'My Boolean Field',
  field: 'BOOLFIELD',
  cellRendererFramework: AgGridCheckbox,
  editable: true,
},

我为这个功能找到了一个很好的在线示例:

https://stackblitz.com/edit/ag-grid-checkbox?embed=1&file=app/ag-grid-checkbox/ag-grid-checkbox.component.html

背景知识基于cellRendererFrameworkhttps://www.ag-grid.com/javascript-grid-components/

尽管这是一个老问题,但我开发了一个可能有趣的解决方案。

您可以为复选框创建一个 cell renderer component,然后将其应用于必须根据 布尔值 值呈现复选框的列。

检查下面的例子:

/*
  CheckboxCellRenderer.js
  Author: Bruno Carvalho da Costa (brunoccst)
*/

/*
 * Function to work as a constructor.
 */
function CheckboxCellRenderer() {}

/**
 * Initializes the cell renderer.
 * @param {any} params Parameters from AG Grid.
 */
CheckboxCellRenderer.prototype.init = function(params) {
  // Create the cell.
  this.eGui = document.createElement('span');
  this.eGui.classList.add("ag-icon");

  var node = params.node;
  var colId = params.column.colId;
  
  // Set the "editable" property to false so it won't open the default cell editor from AG Grid.
  if (params.colDef.editableAux == undefined)
      params.colDef.editableAux = params.colDef.editable;
  params.colDef.editable = false;

  // Configure it accordingly if it is editable.
  if (params.colDef.editableAux) {
    // Set the type of cursor.
    this.eGui.style["cursor"] = "pointer";

    // Add the event listener to the checkbox.
    function toggle() {
      var currentValue = node.data[colId];
      node.setDataValue(colId, !currentValue);

      // TODO: Delete this log.
      console.log(node.data);
    }
    this.eGui.addEventListener("click", toggle);
  }

  // Set if the checkbox is checked.
  this.refresh(params);
};

/**
 * Returns the GUI.
 */
CheckboxCellRenderer.prototype.getGui = function() {
  return this.eGui;
};

/**
 * Refreshes the element according to the current data.
 * @param {any} params Parameters from AG Grid.
 */
CheckboxCellRenderer.prototype.refresh = function(params) {
  var checkedClass = "ag-icon-checkbox-checked";
  var uncheckedClass = "ag-icon-checkbox-unchecked";

  // Add or remove the classes according to the value.
  if (params.value) {
    this.eGui.classList.remove(uncheckedClass);
    this.eGui.classList.add(checkedClass);
  } else {
    this.eGui.classList.remove(checkedClass);
    this.eGui.classList.add(uncheckedClass);
  }

  // Return true to tell the grid we refreshed successfully
  return true;
}

/*
  The code below does not belong to the CheckboxCellRenderer.js anymore.
  It is the main JS that creates the AG Grid instance and structure.
*/

// specify the columns
var columnDefs = [{
  headerName: "Make",
  field: "make"
}, {
  headerName: "Model",
  field: "model"
}, {
  headerName: "Price",
  field: "price"
}, {
  headerName: "In wishlist (editable)",
  field: "InWishlist",
  cellRenderer: CheckboxCellRenderer
}, {
  headerName: "In wishlist (not editable)",
  field: "InWishlist",
  cellRenderer: CheckboxCellRenderer,
  editable: false
}];

// specify the data
var rowData = [{
  make: "Toyota",
  model: "Celica",
  price: 35000,
  InWishlist: true
}, {
  make: "Toyota 2",
  model: "Celica 2",
  price: 36000,
  InWishlist: false
}];

// let the grid know which columns and what data to use
var gridOptions = {
  columnDefs: columnDefs,
  defaultColDef: {
    editable: true
  },
  rowData: rowData,
  onGridReady: function() {
    gridOptions.api.sizeColumnsToFit();
  }
};

// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function() {
  // lookup the container we want the Grid to use
  var eGridDiv = document.querySelector('#myGrid');

  // create the grid passing in the div to use together with the columns & data we want to use
  new agGrid.Grid(eGridDiv, gridOptions);
});
<!DOCTYPE html>
<html>

<head>
  <script src="https://unpkg.com/ag-grid/dist/ag-grid.js"></script>
</head>

<body>
  <div id="myGrid" style="height: 115px;" class="ag-fresh"></div>
</body>

</html>

请注意,我需要在结束 init 函数之前禁用 editable 属性 否则 AG Grid 将呈现该字段的默认单元格编辑器,具有奇怪的行为。

以下是如何在 Angular 中创建 agGrid 单元格渲染器以将您的列之一绑定到复选框。

这个答案主要基于上面 user2010955 的回答中的优秀答案,但有更多的解释,并与最新版本的agGrid & Angular(在添加以下更改之前,我使用他的代码收到错误消息)。

是的,我知道这个问题是关于 agGrid 的 React 版本,但我确定我不会是唯一的 Angular 绝望中偶然发现这个 Whosebug 网页的开发人员,试图找到 Angular 解决此问题的方法。

(顺便说一句,我不敢相信现在是 2020 年,Angular 的 agGrid 没有默认包含复选框渲染器。说真的?!! )

首先,您需要定义一个渲染器组件:

import { Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams } from 'ag-grid-community';

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

    public params: ICellRendererParams; 

    constructor() { }

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

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

    refresh(params: ICellRendererParams): boolean {
        return true;
    }
}

接下来,你需要告诉你的@NgModule:

import { CheckboxCellRenderer } from './cellRenderers/CheckboxCellRenderer';
. . .
@NgModule({
  declarations: [
    AppComponent,
    CheckboxCellRenderer
  ],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([CheckboxCellRenderer])
  ],
  providers: [],
  bootstrap: [AppComponent]
})

在显示 agGrid 的组件中,您需要导入渲染器:

import { CheckboxCellRenderer } from './cellRenderers/CheckboxCellRenderer';

让我们为我们的网格定义一个新的列,其中一些将使用这个新的渲染器:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
    @ViewChild('exampleGrid', {static: false}) agGrid: AgGridAngular;

    columnDefs = [
        { headerName: 'Last name', field: 'lastName', editable: true },
        { headerName: 'First name', field: 'firstName',  editable: true },
        { headerName: 'Subscribed', field: 'subscribed', cellRenderer: 'checkboxCellRenderer' },
        { headerName: 'Is overweight', field: 'overweight', cellRenderer: 'checkboxCellRenderer' }
    ];
    frameworkComponents = {
      checkboxCellRenderer: CheckboxCellRenderer
    }
}

现在,当您创建 agGrid 时,您需要告诉它您正在使用的自制框架组件:

<ag-grid-angular #exampleGrid 
    style="height: 400px;" 
    class="ag-theme-material" 
    [rowData]="rowData"
    [columnDefs]="columnDefs" 
    [frameworkComponents]="frameworkComponents" >
</ag-grid-angular>

呸!

是的...我花了一段时间才弄清楚如何将所有部分组合在一起。 agGrid 自己的网站确实应该包含这样的示例...

gridOptions = {
  onSelectionChanged: (event: any) => {
    let rowData = [];
    event.api.getSelectedNodes().forEach(node => {
      rowDate = [...rowData, node.data];
    });
    console.log(rowData);
  }
}

框架 - React/Angular/Vue.js

通过将单元格渲染器创建为本机框架组件,您可以轻松地将单元格渲染器与任何用于渲染 ag-Grid 的 JavaScript 框架集成。

在下面的代码段中查看 React 中的实现:

export default class extends Component {
  constructor(props) {
    super(props);
    this.checkedHandler = this.checkedHandler.bind(this);
  }
  checkedHandler() {
    let checked = event.target.checked;
    let colId = this.props.column.colId;
    this.props.node.setDataValue(colId, checked);
  }
  render() {
    return (
      <input 
        type="checkbox" 
        onClick={this.checkedHandler}
        checked={this.props.value}
      />
    )
  }
}

注意:将单元格渲染器创建为框架组件时不需要生命周期方法。

创建渲染器后,我们将其注册到 gridOptions.frameworkComponents 中的 ag-Grid 并在所需的列上定义它:

// ./index.jsx

 this.frameworkComponents = {
   checkboxRenderer: CheckboxCellRenderer,
 };

 this.state = {
      columnDefs: [
        // ...
        {
          headerName: 'Registered - Checkbox',
          field: 'registered',
          cellRenderer: 'checkboxRenderer',
        },
        // ...
      ]
      // ....

请查看以下在最流行的 JavaScript 框架(React、Angular、Vue.js)中实现的实时示例:

React demo

Angular demo.
注意:当使用 Angular 时,还需要将自定义渲染器传递给 @NgModule 装饰器以允许依赖注入。

Vue.js demo

原版 JavaScript

您还可以使用 JavaScript 实现复选框渲染器。

在这种情况下,复选框渲染器是使用 JavaScript Class 构建的。 input 元素在 ag-Grid init 生命周期方法(必需)中创建,并且它的 checked 属性设置为将在其中呈现的单元格的基础布尔值。单击事件侦听器添加到复选框每当输入为 checked/unchecked.

时更新此基础单元格值

创建的 DOM 元素在 getGui(必需)生命周期挂钩中返回。我们还在 destroy 可选生命周期挂钩中做了一些清理,我们在其中删除了点击监听器。

function CheckboxRenderer() {}

CheckboxRenderer.prototype.init = function(params) {
  this.params = params;

  this.eGui = document.createElement('input');
  this.eGui.type = 'checkbox';
  this.eGui.checked = params.value;

  this.checkedHandler = this.checkedHandler.bind(this);
  this.eGui.addEventListener('click', this.checkedHandler);
}

CheckboxRenderer.prototype.checkedHandler = function(e) {
  let checked = e.target.checked;
  let colId = this.params.column.colId;
  this.params.node.setDataValue(colId, checked);
}

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

CheckboxRenderer.prototype.destroy = function(params) {
  this.eGui.removeEventListener('click', this.checkedHandler);
}

创建渲染器后,我们只需将其注册到 gridOptions.components 对象中的 ag-Grid:

gridOptions.components = {
  checkboxRenderer: CheckboxRenderer
}

并在所需列上定义渲染器:

gridOptions.columnDefs = [
  // ...
  { 
    headerName: 'Registered - Checkbox',
    field: 'registered',
    cellRenderer: 'checkboxRenderer',
  },
  // ...

请在下面的演示中查看此实现:

Vanilla JavaScript

阅读我们 website or check out our documentation 上的完整博客 post,了解您可以使用 ag-Grid 实现的各种场景。

艾哈迈德·加迪尔 |开发者@ag-Grid

这里是react hooks版本,给这个组件设置columnDef.cellEditorFramework。

import React, {useEffect, forwardRef, useImperativeHandle, useRef, useState} from "react";

export default forwardRef((props, ref) => {
    const [value, setValue] = useState();

    if (value !== ! props.value) {
        setValue(!props.value);
    }

    const inputRef = useRef();
    useImperativeHandle(ref, () => {
        return {
            getValue: () => {
                return value;
            }
        };
    });

    const onChange= e => {
        setValue(!value);
    }

    return (<div  style={{paddingLeft: "15px"}}><input type="checkbox" ref={inputRef} defaultChecked={value} onChange={onChange}  /></div>);
})

我还有下面这个不错的单元格渲染器

       cellRenderer: params => {
            return `<i class="fa fa-${params.value?"check-":""}square-o" aria-hidden="true"></i>`;
        },

您可以保留一个复选框并进行如下编辑:

headerName: 'header name',
field: 'field',
filter: 'agTextColumnFilter',
cellRenderer: params => this.checkBoxCellEditRenderer(params),

然后创建渲染器:

checkBoxCellEditRenderer(params) {
   const input = document.createElement('input');
   input.type = 'checkbox';
   input.checked = params.value;
   input.addEventListener('click', () => {
      params.value = !params.value;
      params.node.data[params.coldDef.field] = params.value;
      // you can add here code

    });
      return input;
}

这是一个老问题,但如果您将 AdapTable 与 AG Grid 结合使用,则会有一个新的答案可用。 只需将列定义为 Checkbox Column,AdapTable 将为您完成所有工作 - 创建复选框,检查单元格值是否为真,并在每次检查时触发一个事件: 参见:https://demo.adaptabletools.com/formatcolumn/aggridcheckboxcolumndemo