任何以pre 前缀(presets、preselectedRows、...)开头的网格选项只能在构建网格时使用(在第一页加载时)。要动态更改行选择,您需要使用 SlickGrid 的其他功能,有两种方法可以做到这一点,它们都非常相似。
另外提醒一下,Angular-Slickgrid 是核心库 SlickGrid 之上的一个包装器,要选择一些行,您需要调用核心库中的 a 方法。
您首先需要获取AngularGridInstance,然后您可以从GridService(它公开SlickGrid 的一些方法)调用setSelectedRows 方法,或者直接从SlickGrid 核心库中使用它。
<!-- Component View -->
<angular-slickgrid
gridId="grid4"
[columnDefinitions]="columnDefinitions"
[gridOptions]="gridOptions"
[dataset]="dataset"
(onAngularGridCreated)="angularGridReady($event)"> <!-- <<== you need this line !-->
</angular-slickgrid>
// Component
export class MyComponent {
angularGrid: AngularGridInstance;
columnDefinitions: Column[];
gridOptions: GridOption;
dataset: any[];
// as the name suggest, this instance will be available
// once the grid finished rendering and is ready
angularGridReady(angularGrid: AngularGridInstance) {
this.angularGrid = angularGrid;
}
changeSelectionDynamically(rowIds: number[]) {
if (this.angularGrid) {
// you can call the method from the GridService
// I prefer to use this because it has the Types (TypeScript)
angularGrid.gridService.setSelectedRows(rowIndexes);
// OR call the method from the SlickGrid object (core lib instance)
angularGrid.slickGrid.setSelectedRows(rowIndexes);
}
}
那么从显示的示例中,我应该选择哪一个?这完全取决于您,您可以使用其中一个,结果将是相同的。我将一些方法复制到 GridService 中的唯一原因仅仅是因为 Angular-Slickgrid 是用 TypeScript 编写的,所以我们有类型检查,而 SlickGrid(核心库)是用纯 JavaScript 编写的,它不会如果您犯了错误,请不要抱怨。
最后,如果您希望在调用一组新选择之前清除您的选择,您可以通过调用一个空数组来实现,如下所示。如果您在新选择之前有任何选择,则必须这样做。
angularGrid.slickGrid.setSelectedRows([]); // first clear the selection
angularGrid.slickGrid.setSelectedRows(rowIndexes); // then set a new selection
编辑
动态选择所有行不能在 1 次执行中完成,因为行选择插件没有任何方法可以做到这一点。但是,可能可行的是从 DataView 获取所有行的 ID(通过 map)。
// actually this won't work since setSelectedRows() is grid row indexed
// so item IDs won't work, so don't use this
const allRowIds = angularGrid.dataView.getItems().map(item => item.id);
angularGrid.slickGrid.setSelectedRows(allRowIds);
注意
这实际上是行不通的,我只记得setSelectedRows 使用网格行索引,而不是项目 ID。但是,您可以做的是获取 dataset 长度并用这些索引填充数组。
const allRowIndexes = Array.from(Array(this.dataset.length).keys());
angularGrid.slickGrid.setSelectedRows(allRowIndexes);
另请注意,我是Angular-Slickgrid 的作者,有关此答案的更多信息,您可以阅读此SlickGrid & DataView objects Wiki。我写了很多 Wiki,而您的问题实际上在这个 Row Selection Wiki 中以另一种方式得到了回答。