Angular Seleção de grade

    Com Ignite UI for Angular Grid, você pode selecionar dados facilmente usando uma variedade de eventos, API avançada ou com interações simples do mouse, como seleção única.

    Angular Grid 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.

    Angular Grid Selection Options

    IgniteUI for Angular Grid component provides three different selection modes - Row selection, Cell selection and Column selection. By default only Multi-cell selection mode is enabled in the Grid. In order to change/enable selection mode you can use rowSelection, cellSelection or selectable properties.

    Angular Row Selection

    Property rowSelection enables you to specify the following options:

    • none - A seleção de linha seria desabilitada para a grade
    • single - A seleção de apenas uma linha dentro da grade estaria disponível
    • multiple - Multi-row selection would be available by using the Row selectors, with a key combination like ctrl + click, or by pressing the space key once a cell is focused

    Vá para o tópico Seleção de linha para obter mais informações.

    Angular Cell Selection

    Property cellSelection enables you to specify the following options:

    • none - A seleção de célula seria desabilitada para a Grade
    • single - A seleção de apenas uma célula dentro da grade estaria disponível.
    • multiple - Atualmente, esse é o estado padrão da seleção na Grade. A seleção de várias células está disponível arrastando o mouse sobre as células, após um clique do botão esquerdo do mouse continuamente.

    Vá para o tópico Seleção de célula para obter mais informações.

    Angular Column Selection

    The selectable property enables you to specify the following options for each column:

    • false - a seleção de coluna correspondente será desativada para a Grade
    • true - a seleção de coluna correspondente será habilitada para a Grade
    • Isso levou às três variações a seguir:
    • Seleção única -mouse click sobre a célula da coluna.
    • Seleção de várias colunas - segurando ctrl + mouse click sobre as células da coluna.
    • Seleção de coluna de intervalo - segurando shift + mouse click seleciona tudo no meio.

    Acesse o tópico Seleção de coluna para obter mais informações.

    Grid Context Menu

    Using the contextMenu event you can add a custom context menu to facilitate your work with IgxGrid. With a right click on the grid's body, the event emits the cell on which it is triggered. The context menu will operate with the emitted cell.

    Se houver uma seleção de várias células, colocaremos lógica, que verificará se a célula selecionada está na área da seleção de várias células. Se for, também emitiremos os valores das células selecionadas.

    Basicamente, a função principal ficará assim:

    public rightClick(eventArgs: any) {
         // Prevent the default behavior of the right click
        eventArgs.event.preventDefault();
        this.multiCellArgs = {};
        // If we have multi-cell selection, check if selected cell is within the ranges
        if (this.multiCellSelection) {
            const node = eventArgs.cell.selectionNode;
            const isCellWithinRange = this.grid1.getSelectedRanges().some(range => {
                if (node.column >= range.columnStart &&
                    node.column <= range.columnEnd &&
                    node.row >= range.rowStart &&
                    node.row <= range.rowEnd) {
                    return true;
                }
                return false;
            })
            // If the cell is within a multi-cell selection range, bind all the selected cells data
            if (isCellWithinRange) {
                this.multiCellArgs = { data: this.multiCellSelection.data };
            }
        }
        // Set the position of the context menu
        this.contextmenuX = eventArgs.event.clientX;
        this.contextmenuY = eventArgs.event.clientY;
        this.clickedCell = eventArgs.cell;
        // Enable the context menu
        this.contextmenu = true;
    }
    

    O menu de contexto terá as seguintes funções:

    • Copie o valor da célula selecionada
    • Copie o dataRow da célula selecionada
    • Se a célula selecionada estiver dentro de um intervalo de seleção de várias células, copie todos os dados selecionados
    //contextmenu.component.ts
    
    public copySelectedCellData(event) {
        const selectedData = { [this.cell.column.field]: this.cell.value };
        this.copyData(JSON.stringify({ [this.cell.column.field]: this.cell.value }));
        this.onCellValueCopy.emit({ data: selectedData });
    }
    
    public copyRowData(event) {
        const selectedData = this.cell.row.data ;
        this.copyData(JSON.stringify(this.cell.row.data));
        this.onCellValueCopy.emit({ data: selectedData });
    }
    
    public copySelectedCells(event) {
        const selectedData = this.selectedCells.data;
        this.copyData(JSON.stringify(selectedData));
        this.onCellValueCopy.emit({ data: selectedData });
    }
    

    O IgxGrid buscará os dados copiados e os colará em um elemento de contêiner.

    O modelo que vamos usar para combinar a grade com o menu de contexto:

    <div class="wrapper">
        <div class="grid__wrapper" (window:click)="disableContextMenu()">
            <igx-grid #grid1 [data]="data" [autoGenerate]="false" height="500px" width="100%"
                (contextMenu)="rightClick($event)" (rangeSelected)="getCells($event)"
                (selected)="cellSelection($event)">
            <!-- Columns area -->
            </igx-grid>
            <div *ngIf="contextmenu==true">
                <contextmenu [x]="contextmenuX" [y]="contextmenuY" [cell]="clickedCell" [selectedCells]="multiCellArgs" (onCellValueCopy)="copy($event)">
                </contextmenu>
            </div>
        </div>
        <div class="selected-data-area">
            <div>
               <pre>{{copiedData}}</pre>
            </div>
        </div>
    </div>
    

    Select multiple cells and press the right mouse button. The context menu will appear and after selecting Copy cells data the selected data will appear in the right empty box. The result is:

    Known Issues and Limitations

    • O uso da Grade com Seleção habilitada no IE11 requer a importação explícita do polyfill da matriz em polyfill.ts do aplicativo angular. O IE11 não é mais suportado a partir da versão 13.0.0.

      import 'core-js/es7/array';
      
    • When the grid has no primaryKey set and remote data scenarios are enabled (when paging, sorting, filtering, scrolling trigger requests to a remote server to retrieve the data to be displayed in the grid), a row will lose the following state after a data request completes:

      • Seleção de linha
      • Expandir/recolher linha
      • Edição de linha
      • Fixação de linha

    API References

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.