Web Components Grid Row Selection
The Ignite UI for Web Components Row Selection feature in Web Components Grid allows users to interactively select, highlight, or deselect a single or multiple rows of data. There are several selection modes available in the IgcGridComponent
:
- Nenhuma seleção
- Seleção múltipla
- Seleção única
Web Components Row Selection Example
The sample below demonstrates the three types of IgcGridComponent
's row selection behavior. Use the drop-down below to enable each of the available selection modes. Use the checkbox to hide or show the row selector checkboxes.
Setup
In order to setup row selection in the IgcGridComponent
, you just need to set the rowSelection
property. This property accepts GridSelectionMode
enumeration.
GridSelectionMode
expõe os seguintes modos:
- Nenhum
- Solteiro
- Múltiplo
Abaixo, veremos cada um deles com mais detalhes.
Nenhuma seleção
In the IgcGridComponent
by default row selection is disabled (rowSelection
is None). So you can not select or deselect a row through interaction with the IgcGridComponent
UI, the only way to complete these actions is to use the provided API methods.
Seleção única
Single row selection can now be easily set up, the only thing you need to do, is to set rowSelection
to Single
property. This gives you the opportunity to select only one row within a grid. You can select a row by clicking on a cell or pressing the space key when you focus on a cell of the row, and of course you can select a row by clicking on the row selector field. When row is selected or deselected RowSelectionChanging
event is emitted.
<igc-grid id="grid" row-selection="Single" auto-generate="true"
allow-filtering="true">
</igc-grid>
constructor() {
const grid = document.getElementById('grid') as IgcGridComponent;
grid.data = this.data;
grid.addEventListener("rowSelectionChanging", this.handleRowSelection);
}
public handleRowSelection(args: IgcRowSelectionEventArgs) {
if (args.detail.added.length && args.detail.added[0] === 3) {
args.detail.cancel = true;
}
}
Seleção múltipla
To enable multiple row selection in the IgcGridComponent
just set the rowSelection
property to Multiple
. This will enable a row selector field on each row and in the IgcGridComponent
header. The row selector allows users to select multiple rows, with the selection persisting through scrolling, paging, and data operations, such as sorting and filtering. The row also can be selected by clicking on a cell or by pressing the space key when a cell is focused. If you have selected one row and click on another while holding the shift key, this will select the whole range of rows. In this selection mode, when you click on a single row, the previous selected rows will be deselected. If you click while holding the ctrl key, the row will be toggled and the previous selection will be preserved.
<igc-grid id="grid" primary-key="ProductID" row-selection="Multiple"
allow-filtering="true" auto-generate="true">
</igc-grid>
Notas
- A seleção de linha acionará o evento
RowSelectionChanging
. Este evento fornece informações sobre a nova seleção, a seleção antiga, as linhas que foram adicionadas e removidas da seleção antiga. Além disso, o evento é cancelável, o que permite que você impeça a seleção. - When row selection is enabled row selectors are displayed, but if you don't want to show them, you can set
hideRowSelectors
to true. - Ao alternar entre os modos de seleção de linha em tempo de execução, isso limpará o estado de seleção de linha anterior.
API usage
Select Rows Programmatically
The code snippet below can be used to select one or multiple rows simultaneously (via primaryKey
). Additionally, the second parameter of this method is a boolean property through which you may choose whether the previous row selection will be cleared or not. The previous selection is preserved by default.
<igc-grid id="grid"
primary-key="ProductID"
row-selection="Multiple"
auto-generate="true">
</igc-grid>
<button id='select'>Select 1,2 and 5</button>
constructor() {
document.getElementById("select").addEventListener("click", this.onClickSelect);
}
public onClickSelect() {
const grid = document.getElementById("grid") as IgcGridComponent;
grid.selectRows([1,2,5], true);
}
This will add the rows which correspond to the data entries with IDs 1, 2 and 5 to the IgcGridComponent
selection.
Deselect Rows
If you need to deselect rows programmatically, you can use the deselectRows
method.
<igc-grid id="grid"
primary-key="ProductID"
row-selection="Multiple"
auto-generate="true">
</igc-grid>
<button id='deselect'>DeSelect</button>
constructor() {
document.getElementById("deselect").addEventListener("click", this.onClickDeselect);
}
public onClickDeselect() {
const grid = document.getElementById("grid") as IgcGridComponent;
grid.deselectRows([1,2,5]);
}
Row Selection Event
Quando há alguma alteração na seleção de linha, o evento RowSelectionChanging
é emitido. RowSelectionChanging
expõe os seguintes argumentos:
OldSelection
- matriz de IDs de linha que contém o estado anterior da seleção de linha.NewSelection
- matriz de IDs de linha que correspondem ao novo estado da seleção de linha.Added
- matriz de IDs de linhas que estão atualmente adicionadas à seleção.Removed
- matriz de IDs de linhas que atualmente são removidas de acordo com o antigo estado de seleção.Event
- o evento original que acionou a alteração na seleção de linha.Cancel
- permite impedir a alteração da seleção de linha.
<igc-grid id="grid">
</igc-grid>
constructor() {
const grid = document.getElementById('grid') as IgcGridComponent;
grid.data = this.data;
grid.addEventListener("rowSelectionChanging", this.handleRowSelectionChange);
}
public handleRowSelectionChange(args) {
args.detail.cancel = true; // this will cancel the row selection
}
Select All Rows
Another useful API method that IgcGridComponent
provides is selectAllRows
. By default this method will select all data rows, but if filtering is applied, it will select only the rows that match the filter criteria. If you call the method with false parameter, SelectAllRows(false)
will always select all data in the grid, even if filtering is applied.
Note Keep in mind that
selectAllRows
will not select the rows that are deleted.
Deselect All Rows
IgcGridComponent
provides a deselectAllRows
method, which by default will deselect all data rows, but if filtering is applied will deselect only the rows that match the filter criteria. If you call the method with false parameter, DeselectAllRows(false)
will always clear all row selection state even if filtering is applied.
How to get Selected Rows
If you need to see which rows are currently selected, you can get their row IDs with the selectedRows
getter.
public getSelectedRows() {
const grid = document.getElementById('grid') as IgcGridComponent;
const currentSelection = grid.selectedRows; // return array of row IDs
}
Additionally, assigning row IDs to selectedRows
will allow you to change the grid's selection state.
public mySelectedRows = [1, 2, 3]; // an array of row IDs
constructor() {
const grid = document.getElementById('grid') as IgcGridComponent;
grid.data = this.data;
grid.selectedRows = this.mySelectedRows;
}
Row Selector Templates
You can template header and row selectors in the IgcGridComponent
and also access their contexts which provide useful functionality for different scenarios.
By default, the IgcGridComponent
handles all row selection interactions on the row selector's parent container or on the row itself, leaving just the state visualization for the template. Overriding the base functionality should generally be done using the RowSelectionChanging event. In case you implement a custom template with a Click
handler which overrides the base functionality, you should stop the event's propagation to preserve the correct row state.
Modelo de linha
To create a custom row selector template, within the igc-grid
you can use the rowSelectorTemplate
property. From the template you can access the implicitly provided context variable, with properties that give you information about the row's state.
A propriedade selected
mostra se a linha atual está selecionada ou não, enquanto a propriedade index
pode ser usada para acessar o índice da linha.
public rowSelectorTemplate = (ctx: IgcRowSelectorTemplateContext) => {
if (ctx.implicit.selected) {
return html`<div style="justify-content: space-evenly;display: flex;width: 70px;">
<span> ${ctx.implicit.index}</span>
<igc-checkbox checked></igc-checkbox>
</div>`;
} else {
return html`<div style="justify-content: space-evenly;display: flex;width: 70px;">
<span> ${ctx.implicit.index}</span>
<igc-checkbox></igc-checkbox>
</div>`;
}
}
The rowID
property can be used to get a reference of an igc-grid
row. This is useful when you implement a click
handler on the row selector element.
public rowSelectorTemplate = (ctx: IgcRowSelectorTemplateContext) => {
return html`
<igc-checkbox
@click="${(event: any) => {
this.onSelectorClick(event, ctx.implicit.key);
}}"
></igc-checkbox>
`;
}
In the above example we are using an IgcCheckboxComponent
and we bind rowContext.selected
to its checked
property. See this in action in our Row Numbering Demo.
Header Template
To create a custom header selector template, within the IgcGridComponent
, you can use the headSelectorTemplate
property. From the template you can access the implicitly provided context variable, with properties that give you information about the header's state.
The SelectedCount
property shows you how many rows are currently selected while totalCount
shows you how many rows there are in the IgcGridComponent
in total.
public headSelectorTemplate = (ctx: IgcHeadSelectorTemplateContext) => {
return html` ${ctx.implicit.selectedCount} / ${ctx.implicit.totalCount} `;
};
As propriedades SelectedCount
e TotalCount
podem ser usadas para determinar se o seletor principal deve ser verificado ou indeterminado (parcialmente selecionado).
<igc-grid id="grid"
primary-key="ProductID"
row-selection="Multiple"
auto-generate="true">
</igc-grid>
constructor() {
const grid = document.getElementById('grid') as IgcGridComponent;
grid.data = this.data;
grid.headSelectorTemplate = this.headSelectorTemplate;
}
public headSelectorTemplate = (ctx: IgcHeadSelectorTemplateContext) => {
const implicit: any = ctx.implicit;
if (implicit.selectedCount > 0 && implicit.selectedCount === implicit.totalCount) {
return html`<igc-checkbox checked></igc-checkbox>`;
} else if (implicit.selectedCount > 0 && implicit.selectedCount !== implicit.totalCount) {
return html`<igc-checkbox indeterminate></igc-checkbox>`;
}
return html`<igc-checkbox></igc-checkbox>`;
}
Row Numbering Demo
This demo shows the usage of custom header and row selectors. The latter uses index
to display row numbers and an IgcCheckboxComponent
bound to selected
.
Excel Style Row Selectors Demo
Esta demonstração usa modelos personalizados para se assemelhar aos seletores de cabeçalho e linha do Excel.
Conditional Selection Demo
Esta demonstração impede que algumas linhas sejam selecionadas usando o evento RowSelectionChanging
e um modelo personalizado com caixa de seleção desabilitada para linhas não selecionáveis.
API References
Additional Resources
- Escolha
- Seleção de células
- Paginação
- Filtragem
- Classificação
- Resumos
- Movimentação de Colunas
- Fixação de coluna
- Redimensionamento de colunas
- Virtualização e desempenho
Nossa comunidade é ativa e sempre acolhedora para novas ideias.