You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中ag-grid列显示单选框,仅单选框触发行选中的实现咨询

Angular Ag-Grid 实现指定列单选框选中行(仅点击单选框触发)

第一步:禁用整行点击选中

先关闭Ag-Grid默认的整行选中行为,确保只有单选框能触发选中逻辑。在gridOptions里配置两个关键参数:

gridOptions: GridOptions = {
  rowSelection: 'single', // 开启单选模式
  suppressRowClickSelection: true, // 禁止点击整行触发选中
  // 其他配置项...
};

第二步:完善自定义单选框单元格组件

基于你已创建的RowSelectionComponent,实现单元格渲染接口,绑定单选框状态并处理点击事件:

组件模板(row-selection.component.html)

<input 
  type="radio" 
  [checked]="params.node.selected" 
  (change)="onRadioChange()"
  name="rowSelectionGroup"
>

组件逻辑(row-selection.component.ts)

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

@Component({
  selector: 'app-row-selection',
  templateUrl: './row-selection.component.html'
})
export class RowSelectionComponent implements ICellRendererAngularComp {
  params!: ICellRendererParams;

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

  // 确保行状态变化时组件自动刷新
  refresh(params: ICellRendererParams): boolean {
    this.params = params;
    return true;
  }

  onRadioChange(): void {
    // 选中当前行
    this.params.node.setSelected(true);
    // 遍历取消其他行选中,严格保证单选逻辑
    this.params.api.forEachNode(node => {
      if (node !== this.params.node) {
        node.setSelected(false);
      }
    });
  }
}

第三步:注册组件并配置列定义

  1. 在模块中声明并将自定义组件注册到Ag-Grid:
import { NgModule } from '@angular/core';
import { AgGridModule } from 'ag-grid-angular';
import { RowSelectionComponent } from './row-selection.component';

@NgModule({
  declarations: [RowSelectionComponent],
  imports: [
    AgGridModule.withComponents([RowSelectionComponent])
  ],
  exports: [RowSelectionComponent]
})
export class YourFeatureModule { }
  1. 在父组件的列定义中使用该自定义渲染器:
columnDefs = [
  {
    headerName: '选择',
    cellRenderer: 'rowSelectionRenderer', // 指定自定义组件别名
    width: 80,
    sortable: false,
    filter: false,
    suppressMenu: true // 禁用列菜单,避免不必要的干扰
  },
  // 业务列示例
  { headerName: '姓名', field: 'name' },
  { headerName: '年龄', field: 'age' }
];

// 在gridOptions中映射组件别名与实际组件
gridOptions: GridOptions = {
  rowSelection: 'single',
  suppressRowClickSelection: true,
  frameworkComponents: {
    rowSelectionRenderer: RowSelectionComponent
  }
};

额外提示

  • 获取选中行:通过this.gridOptions.api.getSelectedRows()可直接获取当前选中的行数据
  • 单选框name属性统一:保证浏览器原生单选行为与Ag-Grid逻辑双重生效
  • 异步数据适配:如果行数据是异步加载,组件的refresh方法会自动同步选中状态

内容的提问来源于stack exchange,提问作者Nitin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:20:27