Angular Seleção de linha de grade

    Com a seleção de linha no Ignite UI for Angular, há uma coluna seletora de linha que precede todas as outras colunas dentro da linha. Quando um usuário clica no seletor de linha, a linha será selecionada ou desmarcada, permitindo que o usuário selecione várias linhas de dados.

    Angular Row Selection Example

    O exemplo abaixo demonstra os três tipos de comportamento de seleção de linha 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. Use o botão de alternância para ocultar ou mostrar a caixa de seleção do seletor de linha.

    Para obter elementos recém-selecionados, você pode usar event.newSelection:

    public handleRowSelection(event: IRowSelectionEventArgs) {
        this.selectedRowsCount = event.newSelection.length;
        this.selectedRowIndex = event.newSelection[0];
        this.snackbarRowCount.open();
        this.snackbar.close();
        this.logAnEvent(`=> 'rowSelectionChanging' with value: ` + JSON.stringify(event.newSelection));
    }
    

    Setup

    In order to setup row selection in the igx-grid, you just need to set the rowSelection property. This property accepts GridSelectionMode enumeration. GridSelectionMode exposes the following three modes: none, single and multiple. Below we will take a look at each of them in more detail.

    None Selection

    In the igx-grid by default row selection is disabled, otherwise ([rowSelection]="'none'"). So you can not select or deselect a row through interaction with the Grid UI, the only way to complete these actions is to use the provided API methods.

    Single Selection

    Single row selection can now be easily set up, the only thing you need to do, is to set [rowSelection] = '"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.

    <!-- selectionExample.component.html -->
    
    <igx-grid [data]="remote | async" [rowSelection]="'single'" [autoGenerate]="true"
              (rowSelectionChanging)="handleRowSelection($event)" [allowFiltering]="true">
    </igx-grid>
    
    /* selectionExample.component.ts */
    
    public handleRowSelection(args) {
        if (args.added.length && args.added[0] === 3) {
            args.cancel = true;
        }
    }
    

    Multiple Selection

    To enable multiple row selection in the igx-grid just set the rowSelection property to multiple. This will enable a row selector field on each row and in the Grid 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.

    <!-- selectionExample.component.html -->
    
    <igx-grid [data]="remote | async" [primaryKey]="'ProductID'" [rowSelection]="'multiple'"
            (rowSelectionChanging)="handleRowSelection($event)" [allowFiltering]="true" [autoGenerate]="true">
    </igx-grid>
    
    <!-- selectionExample.component.ts -->
    
     public handleRowSelection(event: IRowSelectionEventArgs) {
        // use event.newSelection to retrieve primary key/row data of latest selected row
        this.selectedRowsCount = event.newSelection.length;
        this.selectedRowIndex = event.newSelection[0];
     }
    

    Notas

    • In order to have proper row selection and cell selection, while Grid has remote virtualization, a primaryKey should be provided.

    • Quando a Grid tiver virtualização remota, clicar na caixa de seleção do cabeçalho selecionará/desmarcará todos os registros que estão atualmente na grade. Quando novos dados são carregados na Grade sob demanda, as linhas recém-adicionadas não serão selecionadas e isso é uma limitação, portanto, você deve lidar com esse comportamento por conta própria e pode selecionar essas linhas usando os métodos de API fornecidos.

    • Row selection will trigger rowSelectionChanging event. This event gives you information about the new selection, old selection, the rows that have been added and removed from the old selection. Also the event is cancellable, so this allows you to prevent selection.

    • When row selection is enabled row selectors are displayed, but if you don't want to show them, you can set [hideRowSelectors] = 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.

    <!-- selectionExample.component.html -->
    
    <igx-grid ... [primaryKey]="'ID'">
    ...
    </igx-grid>
    ...
    <button (click)="this.grid.selectRows([1,2,5], true)">Select 1,2 and 5</button> // select rows and clear previous selection state
    

    Isso adicionará as linhas que correspondem às entradas de dados com IDs 1, 2 e 5 à seleção de Grade.

    Deselect rows

    If you need to deselect rows programmatically, you can use the deselectRows(rowIds: []) method.

    <!-- selectionExample.component.html -->
    
    <igx-grid ... [primaryKey]="'ID'">
    ...
    </igx-grid>
    ...
    <button (click)="this.grid.deselectRows([1,2,5])">Deselect 1,2 and 5</button>
    

    Row selection event

    When there is some change in the row selection rowSelectionChanging event is emitted. rowSelectionChanging exposes the following arguments:

    • oldSelection - array of row's data that contains the previous state of the row selection.
    • newSelection - array of row's data that match the new state of the row selection.
    • added - array of row's data that are currently added to the selection.
    • removed - array of row's data that are currently removed according old selection state.
    • event - the original event that triggered row selection change.
    • cancel - allows you the prevent the row selection change.

    Evento de seleção de linha em cenários de dados remotos

    In remote data scenarios, when the grid has a primaryKey set, rowSelectionChanging.oldSelection event argument will not contain the full row data object for the rows that are currently out of the data view. In this case, rowSelectionChanging.oldSelection object will contain only one property, which is the primaryKey field. For the rest of the rows, currently in the data view, rowSelectionChanging.oldSelection will contain the whole row data.

    <!-- selectionExample.component.html -->
    
    <igx-grid (rowSelectionChanging)="handleRowSelectionChange($event)">
    ...
    </igx-grid>
    
    /* selectionExample.component.ts */
    
    public handleRowSelectionChange(args) {
        args.cancel = true; // this will cancel the row selection
    }
    
    

    Select all rows

    Another useful API method that igx-grid provides is selectAll(onlyFilteredData). 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. But if you call the method with false parameter, selectAll(false) will always select all data in the grid, even if filtering is applied.

    Note

    Keep in mind that selectAll() will not select the rows that are deleted.

    Deselect all rows

    igx-grid provides deselectAll(onlyFilteredData) method, which by default will deselect all data rows, but if filtering is applied will deselect only the rows that match the filter criteria. But if you call the method with false parameter, deselectAll(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 currentSelection = this.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
    
    <igx-grid primaryKey="ProductID" rowSelection="multiple" [autoGenerate]="false" [mySelectedRows]="selectedRows" [data]="data">
        <igx-column [field]="'ProductID'"></igx-column>
        <igx-column [field]="'ProductName'"></igx-column>
        <igx-column [field]="'UnitsInStock'"></igx-column>
    </igx-grid>
    

    Row selector templates

    Você pode modelar seletores de cabeçalho e linha na Grade e também acessar seus contextos que fornecem funcionalidade útil para diferentes cenários.

    By default, the Grid 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 igx-grid, declare an <ng-template> with igxRowSelector directive. From the template you can access the implicitly provided context variable, with properties that give you information about the row's state.

    The selected property shows whether the current row is selected or not while the index property can be used to access the row index.

    <ng-template igxRowSelector let-rowContext>
        {{ rowContext.index }}
        <igx-checkbox
            [checked]="rowContext.selected"
            [readonly]="true"
        ></igx-checkbox>
    </ng-template>
    

    The rowID property can be used to get a reference of an igx-grid row. This is useful when you implement a click handler on the row selector element.

    <ng-template igxRowSelector let-rowContext>
        <igx-checkbox (click)="onSelectorClick($event, rowContext.key)"></igx-checkbox>
    </ng-template>
    

    In the above example we are using an igx-checkbox 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 Grid, declare an <ng-template> with igxHeadSelector directive. 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 Grid in total.

    <ng-template igxHeadSelector let-headContext>
        {{ headContext.selectedCount }} / {{ headContext.totalCount  }}
    </ng-template>
    

    The selectedCount and totalCount properties can be used to determine if the head selector should be checked or indeterminate (partially selected).

    <igx-grid [data]="gridData" primaryKey="ProductID" rowSelection="multiple">
        <!-- ... -->
        <ng-template igxHeadSelector let-headContext>
            <igx-checkbox
                [checked]=" headContext.selectedCount > 0 && headContext.selectedCount === headContext.totalCount"
                [indeterminate]="headContext.selectedCount > 0 && headContext.selectedCount !== headContext.totalCount">
            </igx-checkbox>
        </ng-template>
    </igx-grid>
    

    Row Numbering Demo

    This demo shows the usage of custom header and row selectors. The latter uses rowContext.index to display row numbers and an igx-checkbox bound to rowContext.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

    This demo prevents some rows from being selected using the rowSelectionChanging event and a custom template with disabled checkbox for non-selectable rows.

    API References

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.