37

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

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

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

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

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

4

20 回答 20

36

您应该使用 cellRenderer 属性

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

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

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

但就我而言,我决定帮助你,我知道它并没有 100% 解决所有问题,但至少它解决了数据呈现部分。

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

于 2017-02-27T17:39:44.057 回答
16

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

让我知道

于 2017-10-24T13:45:58.807 回答
14

我们可以使用 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;
    }
}
于 2019-03-14T03:15:50.520 回答
8

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

这个答案很大程度上基于user2010955上面的答案的出色答案,但有更多解释,并与最新版本的 agGrid 和 Angular 保持同步(在添加之前,我使用他的代码收到错误以下更改)。

是的,我知道这个问题是关于 agGrid 的React版本的,但我敢肯定,我不会是唯一一个绝望地偶然发现这个 StackOverflow 网页并试图找到解决这个问题的 Angular的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 自己的网站确实应该包含这样的示例...

于 2020-04-23T08:57:54.050 回答
7

下面的代码有助于解决这个问题。缺点是不会触发 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;
  };
于 2018-02-21T21:32:09.947 回答
6

反应具体解决方案

当使用带有 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>
  );
}

在您的网格中使用它

调整您的列 def ( ColDef) 以使用此单元格渲染器。

{
  headerName: 'My Boolean Field',
  field: 'BOOLFIELD',
  cellRendererFramework: AgGridCheckbox,
  editable: true,
},
于 2020-01-24T19:07:50.020 回答
4

框架 - 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}
      />
    )
  }
}

注意:将单元格渲染器创建为框架组件时,没有必需的生命周期方法。

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

// ./index.jsx

 this.frameworkComponents = {
   checkboxRenderer: CheckboxCellRenderer,
 };

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

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

反应演示

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

Vue.js 演示

香草 JavaScript

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

在这种情况下,复选框渲染器是使用 JavaScript 类构造的。在 ag-Grid 生命周期方法中创建了一个输入元素init(必需),并将其选中属性设置为将在其中呈现的单元格的底层布尔值。单击事件侦听器被添加到复选框中,用于更新此底层单元格值每当输入被选中/未选中时。

创建的 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',
  },
  // ...

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

香草 JavaScript

阅读我们网站上的完整博客文章或查看我们的文档,了解您可以使用 ag-Grid 实现的各种场景。

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

于 2020-06-03T12:49:00.270 回答
2

这是一个 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>`;
        },
于 2020-06-15T00:01:01.657 回答
2

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

于 2021-08-03T11:52:18.860 回答
1

在 columnDefs 中,添加一个复选框列。不需要将单元格属性可编辑设置为 true

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

复选框渲染器

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>);
    }
}
于 2017-04-21T12:54:16.887 回答
1

字符串值的数组对我不起作用,但 [true,false] 的数组正在工作。

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

function RefundedCellRenderer(params) {
    return params.value;
}
于 2018-01-31T01:03:55.500 回答
1
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;
于 2019-01-30T20:12:00.687 回答
1

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

我试试这个,它的工作:

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);
    })
});
于 2019-07-07T19:53:48.240 回答
1

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

您可以为复选框创建一个单元格渲染器组件,然后将其应用于必须基于布尔值呈现复选框的列。

检查以下示例:

/*
  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函数之前禁用可编辑属性,否则 AG Grid 将呈现该字段的默认单元格编辑器,从而产生奇怪的行为。

于 2020-03-02T14:42:08.737 回答
0

当前部分的布尔数据:

    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"}]')));
于 2019-03-04T11:45:02.157 回答
0

这是一个对我有用的解决方案。必须尊重箭头函数来解决上下文问题。

零件:

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>
于 2020-01-18T10:55:25.723 回答
0

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

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/

于 2020-02-28T10:20:50.347 回答
0
gridOptions = {
  onSelectionChanged: (event: any) => {
    let rowData = [];
    event.api.getSelectedNodes().forEach(node => {
      rowDate = [...rowData, node.data];
    });
    console.log(rowData);
  }
}
于 2020-05-06T03:45:20.950 回答
0

您可以保持显示复选框并进行如下编辑:

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;
}
于 2020-06-16T16:57:37.513 回答
-5

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

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

function RefundedCellRenderer(params) {
    return params.value;
}
于 2017-03-10T01:35:05.263 回答