Angular Tree Grid Row Selection

    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 quatro tipos de comportamento de seleção de linha da Grade de Árvore. 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.

    Setup

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

    None Selection

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

    Single Selection

    A seleção de uma única linha agora pode ser facilmente configurada, a única coisa que você precisa fazer é definir[rowSelection] = '"single"' a propriedade. Isso te dá a oportunidade de selecionar apenas uma linha dentro de uma grade. Você pode selecionar uma linha clicando em uma célula ou pressionando a tecla espaço ao focar em uma célula da linha, e claro, pode selecionar uma linha clicando no campo seletor de linhas. Quando a linha é selecionada ou desmarcada é emitido um evento de mudança de linhaSeleção.

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

    Multiple Selection

    To enable multiple row selection in the igx-tree-grid just set the rowSelection property to multiple. This will enable a row selector field on each row and in the Tree 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-tree-grid [data]="data" primaryKey="ID" foreignKey="ParentID" [rowSelection]="'multiple'"
            [allowFiltering]="true" (rowSelectionChanging)="handleRowSelection($event)" >
    </igx-tree-grid>
    

    Cascade Selection

    To enable cascade row selection in the igx-tree-grid just set the rowSelection property to multipleCascade. This will enable a row selector field on each row and in the Tree Grid header. The row selector allows users to select multiple rows which would select all children in the tree below. The selection persists through scrolling, paging, and data operations, such as sorting and filtering. The row can also 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, the selection of a parent record will select all of its children even if they are not in the selected range. In this selection mode, when you click on a single row, the previously selected rows will be deselected. If you click while holding the ctrl key, the row and its children will be toggled and the previous selection will be preserved.

    <!-- selectionExample.component.html -->
    
    <igx-tree-grid [data]="data" primaryKey="ID" foreignKey="ParentID" [autoGenerate]="true"
            [rowSelection]="'multipleCascade'" [allowFiltering]="true" (rowSelectionChanging)="handleRowSelection($event)">
    </igx-tree-grid>
    

    Nesse modo, o estado de seleção de um pai depende inteiramente do estado de seleção de seus filhos. Quando um pai tem alguns filhos selecionados e alguns desmarcados, sua caixa de seleção está em um estado indeterminado.

    <!-- 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

    • A seleção de linha vai acionarrowSelectionChanging o evento. Este evento te dá 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 pode ser cancelado, então isso permite evitar a seleção.
    • Quando a seleção de linhas está ativada, os seletores de fileiras são exibidos, mas se você não quiser mostrá-los, pode configurar[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

    O trecho de código abaixo pode ser usado para selecionar uma ou várias linhas simultaneamente (viaprimaryKey); Além disso, o segundo parâmetro desse método é uma propriedade booleana pela qual você pode escolher se a seleção da linha anterior será eliminada ou não. A seleção anterior é preservada por padrão.

    <!-- selectionExample.component.html -->
    
    <igx-tree-grid ... [primaryKey]="'ID'">
    ...
    </igx-tree-grid>
    ...
    <button (click)="this.treeGrid.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 de árvore.

    Deselect rows

    Se precisar desmarcar as linhas programaticamente, pode usar odeselectRows(rowIds: []) método.

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

    Row selection event

    Quando há alguma mudança na seleçãorowSelectionChanging de linha, é emitido um evento.rowSelectionChanging expõe os seguintes argumentos:

    • oldSelection- array de dados de linhas que contém o estado anterior da seleção de linha.
    • newSelection- array de dados de linhas que correspondem ao novo estado da seleção da linha.
    • added- array de dados de linhas que são atualmente adicionados à seleção.
    • removed- array de dados de linhas que atualmente são removidos de acordo com o estado de seleção antigo.
    • event- o evento original que desencadeou a mudança na seleção de linha.
    • cancel- permite impedir a mudança de seleção de linha.

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

    Em cenários de dados remotos, quando a grade tem umprimaryKey argumento set,rowSelectionChanging.oldSelection evento não conterá o objeto de dados da linha completa para as linhas que estão atualmente fora da visualização de dados. Nesse caso,rowSelectionChanging.oldSelection objeto conterá apenas uma propriedade, que é oprimaryKey campo. Para o restante das linhas, atualmente na visualização de dados,rowSelectionChanging.oldSelection conterá os dados da linha inteira.

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

    Select all rows

    Outro método útil de API queigx-tree-grid oferece éselectAll(onlyFilteredData). Por padrão, esse método seleciona todas as linhas de dados, mas se for aplicado filtro, ele seleciona apenas as linhas que correspondem aos critérios do filtro. Mas se você chamar o método com parâmetro falso,selectAll(false) sempre selecionará todos os dados na grade, mesmo que seja aplicado filtro.

    Note

    Lembre-se de que issoselectAll() não selecionará as linhas que são deletadas.

    Deselect all rows

    igx-tree-gridfornecedeselectAll(onlyFilteredData) o método, que por padrão desmarca todas as linhas de dados, mas se for aplicado filtragem, desmarca apenas as linhas que correspondem aos critérios do filtro. Mas se você chamar o método com parâmetro falso,deselectAll(false) sempre vai limpar todo o estado de seleção de linha, mesmo que seja aplicado filtro.

    How to get selected rows

    Se você precisar ver quais linhas estão selecionadas no momento, pode pegar os IDs de linha delas com oselectedRows getter.

    
    public getSelectedRows() {
        const currentSelection = this.treeGrid.selectedRows; // return array of row IDs
    }
    

    Além disso, atribuir IDs de linha permiteselectedRows que você mude o estado de seleção da grade.

    public mySelectedRows = ['Johnathan Winchester', 'Ana Sanders']; // an array of row IDs
    
    <igx-tree-grid primaryKey="ID" rowSelection="multiple" [autoGenerate]="false" [selectedRows]="mySelectedRows" [data]="data">
        <igx-column [field]="'Name'"></igx-column>
        <igx-column [field]="'Title'"></igx-column>
    </igx-tree-grid>
    

    Row selector templates

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

    By default, the Tree 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

    Para criar um modelo seletor de linhas personalizado, dentro de,igx-tree-grid declare uma<ng-template> diretiva withigxRowSelector. A partir do template, você pode acessar a variável de contexto implicitamente fornecida, com propriedades que fornecem informações sobre o estado da linha.

    Aselected propriedade mostra se a linha atual está selecionada ou não, enquanto aindex propriedade pode ser usada para acessar o índice de linhas.

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

    ArowID propriedade pode ser usada para obter uma referência de umaigx-tree-grid linha. Isso é útil quando você implementa umclick handler no elemento seletor de linhas.

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

    No exemplo acima, estamos usando umigx-checkbox e nós ligamosrowContext.selected à suachecked propriedade. Veja isso em ação em nossaRow Numbering Demo.

    Header template

    To create a custom header selector template, within the Tree 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 Tree Grid in total.

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

    AsselectedCount propriedades etotalCount podem ser usadas para determinar se o seletor de cabeça deve ser verificado ou indeterminado (parcialmente selecionado).

    <igx-tree-grid [data]="tGridData" primaryKey="ProductID" childDataKey="Products">
        <!-- ... -->
        <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-tree-grid>
    

    Row Numbering Demo

    Esta demonstração mostra o uso de seletores personalizados de cabeçalho e linha. Este último é usadorowContext.index para exibir números de linha e umigx-checkbox bound torowContext.selected.

    Conditional Selection Demo

    Esta demonstração impede que algumas linhas sejam selecionadas usando orowSelectionChanging evento e um modelo personalizado com a caixa de seleção desativada para linhas não selecionáveis.

    API References

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.