以下是一个使用Ag Grid分组显示数据的示例代码:
HTML代码:
JavaScript代码:
// 创建Ag Grid实例
var gridOptions = {
columnDefs: [
{ headerName: "姓名", field: "name", rowGroup: true },
{ headerName: "年龄", field: "age" },
{ headerName: "性别", field: "gender" },
{ headerName: "城市", field: "city", rowGroup: true },
],
autoGroupColumnDef: { minWidth: 200 },
rowSelection: 'single',
groupSelectsChildren: true,
groupDefaultExpanded: 1,
animateRows: true,
rowData: [
{ name: "张三", age: 25, gender: "男", city: "北京" },
{ name: "李四", age: 30, gender: "男", city: "上海" },
{ name: "王五", age: 28, gender: "女", city: "北京" },
{ name: "赵六", age: 35, gender: "男", city: "上海" },
{ name: "钱七", age: 27, gender: "女", city: "北京" },
{ name: "孙八", age: 32, gender: "男", city: "上海" }
],
};
// 将Grid绑定到HTML元素
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
上述代码创建了一个Ag Grid实例,并将其绑定到id为"myGrid"的HTML元素上。通过设置columnDefs属性来定义列的属性,其中rowGroup属性用于指定需要进行分组的列。autoGroupColumnDef属性用于设置自动分组的列的样式。其他属性用于定义行选择、默认展开等行为。
最后,通过设置rowData属性来传入需要显示的数据。
注意:在使用上述代码之前,请确保已经引入了Ag Grid的相关依赖文件,并正确配置了相关的样式表。