Angular 10中如何通过编程方式选中Kendo Grid表格行?
嘿,针对你在Angular 10里想要编程式选中Kendo Grid行的需求,我给你整理了两种靠谱的实现方式,尤其是选中第三行的具体操作,一起来看看:
方法一:通过绑定
selectedKeys实现(最推荐) Kendo Grid的行选中功能核心依赖selectedKeys数组和kendoGridSelectBy指令,这种方式符合Angular的响应式编程思路,代码更简洁易维护。
步骤1:配置Grid模板
首先要在Grid标签里开启选中模式,并绑定相关属性:
<kendo-grid [data]="gridData" [selectable]="{ mode: 'single' }" <!-- 单选模式,多选改成'multiple'即可 --> [selectedKeys]="selectedRowKeys" kendoGridSelectBy="id" <!-- 替换成你数据项里的唯一标识字段,比如code、uid等 --> > <!-- 你的列配置 --> <kendo-grid-column field="name" title="名称"></kendo-grid-column> <kendo-grid-column field="value" title="数值"></kendo-grid-column> </kendo-grid>
步骤2:组件类里编程选中第三行
在组件中定义selectedRowKeys数组,然后通过修改这个数组来控制选中状态:
import { Component } from '@angular/core'; @Component({ selector: 'app-grid-demo', templateUrl: './grid-demo.component.html' }) export class GridDemoComponent { // 模拟Grid数据源 public gridData = [ { id: 1, name: '第一行数据', value: 100 }, { id: 2, name: '第二行数据', value: 200 }, { id: 3, name: '第三行数据', value: 300 }, { id: 4, name: '第四行数据', value: 400 } ]; // 存储选中行的唯一标识 public selectedRowKeys: number[] = []; // 调用此方法即可选中第三行 selectThirdRow(): void { // 数组索引从0开始,第三行对应索引2 const thirdRowId = this.gridData[2].id; // 单选模式下直接替换数组;多选模式可push或按需切换状态 this.selectedRowKeys = [thirdRowId]; } }
方法二:通过Grid的
SelectionService实现(更灵活的底层操作) 如果需要更精细的选中控制(比如批量操作、动态切换选中状态),可以直接使用Grid内置的SelectionService。
步骤1:给Grid添加模板引用
<kendo-grid #myGrid [data]="gridData" [selectable]="{ mode: 'single' }" > <!-- 列配置... --> </kendo-grid>
步骤2:注入Service并操作选中
import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { GridComponent, SelectionService } from '@progress/kendo-angular-grid'; @Component({ selector: 'app-grid-demo', templateUrl: './grid-demo.component.html' }) export class GridDemoComponent implements AfterViewInit { public gridData = [ { id: 1, name: '第一行数据', value: 100 }, { id: 2, name: '第二行数据', value: 200 }, { id: 3, name: '第三行数据', value: 300 }, { id: 4, name: '第四行数据', value: 400 } ]; @ViewChild('myGrid') private grid: GridComponent; private selectionService: SelectionService; ngAfterViewInit(): void { // 必须在视图初始化后获取SelectionService实例 this.selectionService = this.grid.selectionService; } selectThirdRow(): void { const thirdRowItem = this.gridData[2]; // 选中指定数据项 this.selectionService.select(thirdRowItem); // 取消选中可调用 this.selectionService.deselect(thirdRowItem) // 多选模式下可传入数组批量选中:this.selectionService.select([item1, item2]) } }
注意事项
- 一定要确保Grid开启了
selectable配置,否则选中功能不会生效 - 使用
selectedKeys方式时,kendoGridSelectBy指定的字段必须是数据项的唯一标识,否则Kendo无法正确匹配行 - 如果你的Grid用了复选框列(
<kendo-grid-checkbox-column>),以上两种方法同样适用,底层逻辑是一致的
内容的提问来源于stack exchange,提问作者user13889515
相关产品推荐
相关产品推荐

