Angular Seleção de células
The selection feature enables rich data select capabilities in the Material UI based Grid. Variety of events and single select actions are available thanks to the powerful API and easy to use methods. The Grid now supports three modes for cell selection, and you can easily switch between them by changing cellSelection property. You can disable cell selection, you can select only one cell within the grid or to select multiple cells in the grid, which is provided as default option.
But let's dive deeper in each of these options.
Angular Cell Selection Example
O exemplo abaixo demonstra os três tipos de comportamento de seleção de células do Grid. Use os botões abaixo para ativar cada um dos modos de seleção disponíveis. Uma breve descrição será fornecida em cada interação do botão por meio de uma caixa de mensagem de lanchonete.
Selection types
Grid Multiple-cell Selection
Como selecionar células:
- By
Mouse drag- Rectangular data selection of cells would be performed. - By
Ctrl keypress +Mouse drag- Multiple range selections would be performed. Any other existing cell selection will be persisted. - Instant multi-cell selection by using Shift key. Select single cell and select another single cell by holding the Shift key. Cell range between the two cells will be selected. Keep in mind that if another second cell is selected while holding
Shift keythe cell selection range will be updated based on the first selected cell position (starting point). - Keyboard multi-cell selection by using the
Arrow keyswhile holdingShift key. Multi-cell selection range will be created based on the focused cell. - Keyboard multi-cell selection by using the
Ctrl + Arrow keysandCtrl + Home/Endwhile holdingShift key. Multi-cell selection range will be created based on the focused cell. - Clicking with the
Left Mouse keywhile holdingCtrl keywill add single cell ranges into the selected cells collection. - A seleção contínua de múltiplas células está disponível clicando com o mouse e arrastando.
Demo
Grid Single Selection
When you set the [cellSelection]="'single'", this allows you to have only one selected cell in the grid at a time. Also the mode mouse drag will not work and instead of selecting a cell, this will make default text selection.
Note
When single cell is selected selected event is emitted, no matter if the selection mode is single or multiple. In multi-cell selection mode when you select a range of cells rangeSelected event is emitted.
Grid None selection
If you want to disable cell selection you can just set [cellSelection]="'none'" property. In this mode when you click over the cell or try to navigate with keyboard, the cell is not selected, only the activation style is applied and it is going to be lost when you scroll or click over other element on the page. The only way for you to define selection is by using the API methods that are described below.
Keyboard navigation interactions
While Shift key is pressed
- Shift + Arrow Up para adicionar a célula acima à seleção atual.
- Shift + Arrow Down para adicionar a célula abaixo à seleção atual.
- Shift + Arrow Left para adicionar a célula esquerda à seleção atual.
- Shift + Arrow Right para adicionar a célula direita à seleção atual.
While Ctrl + Shift keys are pressed
- Ctrl + Shift + Arrow Up para selecionar todas as células acima da célula focalizada na coluna.
- Ctrl + Shift + Arrow Down para selecionar todas as células abaixo da célula focalizada na coluna.
- Ctrl Arrow Left + Shift +para selecionar todas as células até o início da linha.
- Ctrl + Shift + Arrow Right para selecionar todas as células até o final da linha.
- Ctrl + Shift + Home para selecionar todas as células, desde a célula em foco até a primeira célula na grade
- Ctrl + Shift + End para selecionar todas as células, desde a célula em foco até a última célula da grade
Note
A rolagem contínua só é possível dentro do corpo do Grid.
Api usage
Abaixo estão os métodos que você pode usar para selecionar intervalos, limpar a seleção ou obter dados de células selecionadas.
Select range
selectRange(range) - Select a range of cells with the API. rowStart and rowEnd should use row indexes and columnStart and columnEnd could use column index or column data field value.
const range = { rowStart: 2, rowEnd: 2, columnStart: 1, columnEnd: 1 };
this.grid1.selectRange(range);
...
const range = { rowStart: 0, rowEnd: 2, columnStart: 'Name', columnEnd: 'ParentID' };
this.grid1.selectRange(range);
Note
Selecionar intervalo é uma operação aditiva. Isso não limpará sua seleção anterior.
Clear cell selection
clearCellSelection() will clear the current cell selection.
Get selected data
getSelectedData() will return array of the selected data in format depending on the selection. Examples below:
Se três células individuais diferentes forem selecionadas:
expectedData = [ { CompanyName: 'Infragistics' }, { Name: 'Michael Langdon' }, { ParentID: 147 } ];Se três células de uma coluna forem selecionadas:
expectedData = [ { Address: 'Obere Str. 57'}, { Address: 'Avda. de la Constitución 2222'}, { Address: 'Mataderos 2312'} ];Se três células forem selecionadas com o arrastar do mouse de uma linha e três colunas:
expectedData = [ { Address: 'Avda. de la Constitución 2222', City: 'México D.F.', ContactTitle: 'Owner' } ];Se três células forem selecionadas com o mouse arrastando de duas linhas e três colunas:
expectedData = [ { ContactTitle: 'Sales Agent', Address: 'Cerrito 333', City: 'Buenos Aires'}, { ContactTitle: 'Marketing Manager', Address: 'Sierras de Granada 9993', City: 'México D.F.'} ];Se dois intervalos diferentes forem selecionados:
expectedData = [ { ContactName: 'Martín Sommer', ContactTitle: 'Owner'}, { ContactName: 'Laurence Lebihan', ContactTitle: 'Owner'}, { Address: '23 Tsawassen Blvd.', City: 'Tsawassen'}, { Address: 'Fauntleroy Circus', City: 'London'} ];Se dois intervalos sobrepostos forem selecionados, o formato será:
expectedData = [ { ContactName: 'Diego Roel', ContactTitle: 'Accounting Manager', Address: 'C/ Moralzarzal, 86'}, { ContactName: 'Martine Rancé', ContactTitle: 'Assistant Sales Agent', Address: '184, chaussée de Tournai', City: 'Lille'}, { ContactName: 'Maria Larsson', ContactTitle: 'Owner', Address: 'Åkergatan 24', City: 'Bräcke'}, { ContactTitle: 'Marketing Manager', Address: 'Berliner Platz 43', City: 'München'} ];
Note
selectedCells() will return cells from all visible rows (rows in the grid's view port) and from all columns, including columns that are out of view. getSelectedData() will also return the selected cell data.
getSelectedRanges(): GridSelectionRange[] will return the current selected ranges in the grid from both keyboard and pointer interactions. The type is GridSelectionRange[].
Features integration
A seleção de múltiplas células é baseada em índice (seleção de elementos DOM).
Sorting- When sorting is performed selection will not be cleared. It will leave currently selected cells the same while sorting ascending or descending.Paging- On paging selected cells will be cleared. Selection wont be persisted across pages.Filtering- When filtering is performed selection will not be cleared. If filtering is cleared it will return - the initially selected cells.Resizing- On column resizing selected cells will not be cleared.Hiding- It will not clear the selected cells. If column is hidden, the cells from the next visible column will be selected.Pinning- Selected cell will not be cleared. Same as hidingGroup by- On column grouping selected cells will not be cleared.
Estilização
O mecanismo de tema expõe propriedades que nos permitem estilizar o intervalo de células selecionadas.
Import theme
To get started with styling the selection, we need to import the index file, where all the theme functions and component mixins live:
@use "igniteui-angular/theming" as *;
// IMPORTANT: Prior to Ignite UI for Angular version 13 use:
// @import '~igniteui-angular/lib/core/styles/themes/index';
Define colors
Once done, we can make use of the contrast-color and color functions. With them, we define the colors we would like to use for our selection range:
$text-color: contrast-color($color: 'primary', $variant: 900);
$background-color: color($color: "primary", $variant: 900);
$border-yellow: #f2c43c;
Note
If we don't want to use the contrast-color and color functions, we can always hardcode the color values.
Create custom theme
Next we create a new theme that extends the grid-theme passing our text-color, background-color and border-yellow variables as $cell-selected-text-color, $cell-selected-background and $cell-active-border-color, respectively:
$custom-grid-theme: grid-theme(
$cell-selected-text-color: $text-color,
$cell-active-border-color: $border-yellow,
$cell-selected-background: $background-color
);
Apply theme
Depois, tudo o que precisamos fazer é incluir o mixin no estilo do nosso componente (também pode estar nos estilos do aplicativo), para que nosso igx-grid use o tema recém-criado em vez do padrão:
@include css-vars($custom-grid-theme);
Com o tema personalizado aplicado, as células de grade selecionadas são destacadas com nossas cores selecionadas:
Demo
Note
A amostra não será afetada pelo tema global selecionado deChange Theme.
API References
Additional Resources
- Visão geral da grade
- Escolha
- Seleção de linha
- Filtragem
- Classificação
- Resumos
- Movimentação de Colunas
- Fixação de coluna
- Redimensionamento de colunas
- Virtualização e desempenho