Angular Edição de linha de grade

    O Grid fornece uma maneira conveniente de realizar manipulações de dados por meio de edição em linha e uma API poderosa para operações CRUD Angular. Clique em uma linha e pressione a tecla Enter ou simplesmente clique duas vezes com o mouse na linha que precisa ser modificada.

    Angular Grid Row Editing Example

    O exemplo a seguir demonstra como habilitar a edição de linha na Grade. Alterar um valor de célula e, em seguida, clicar ou navegar para outra célula na mesma linha não atualizará o valor da linha até que seja confirmado usando o botão Concluído ou descartado usando o botão Cancelar.

    Note

    Quando uma linha está no modo de edição, clicar em uma célula em outra linha agirá como se o botão Concluído estivesse pressionado - envie todas as alterações da linha anterior. Se a nova célula que recebe o foco for editável, a nova linha também entrará no modo de edição, enquanto se a célula não for editável, apenas a linha anterior sairá do modo de edição.

    Row Editing Usage

    Para começar, importe oIgxGridModule arquivo no app.module.ts:

    // app.module.ts
    
    ...
    import { IgxGridModule } from 'igniteui-angular';
    
    @NgModule({
        ...
        imports: [..., IgxGridModule],
        ...
    })
    export class AppModule {}
    

    Then define a Grid with bound data source and rowEditable set to true:

    <igx-grid [data]="data" [primaryKey]="'ProductID'" width="100%" height="500px" [rowEditable]="true">
        <igx-column field="ProductID" header="Product ID" editable="false"></igx-column>
        <igx-column field="ReorderLevel" header="ReorderLever" [dataType]="'number'"></igx-column>
        <igx-column field="ProductName" header="ProductName" [dataType]="'string'"></igx-column>
        <igx-column field="UnitsInStock" header="UnitsInStock" [dataType]="'number'">
            <ng-template igxCellEditor let-cell="cell">
                <input name="units" [(ngModel)]="cell.value" style="color: black" />
            </ng-template>
        </igx-column>
        <igx-column field="OrderDate" [dataType]="'date'"></igx-column>
        <igx-column field="Discontinued" header="Discontinued" [dataType]="'boolean'"></igx-column>
    </igx-grid>
    
    Note

    A configuração da chave primária é obrigatória para operações de edição de linha.

    Note

    It's not needed to enable editing for individual columns. Using the rowEditable property in the Grid, will mean that all rows, with defined field property, excluding primary one, will be editable. If you want to disable editing for specific column, then you set the editable column's input to false.

    import { Component, ViewChild } from '@angular/core';
    import { data } from './data';
    import { IgxGridComponent } from 'igniteui-angular';
    // import { IgxGridComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-grid-row-edit',
        styleUrls: [`grid-row-editing-sample.component.css`],
        templateUrl: 'grid-row-editing-sample.component.html'
    })
    export class GridRowEditSampleComponent {
        @ViewChild('gridRowEdit', { read: IgxGridComponent }) public gridRowEdit: IgxGridComponent;
    
        public data: any[];
    
        constructor() {
            this.data = data;
        }
    }
    
    Note

    The Grid uses internally a provider IgxBaseTransactionService that holds pending cell changes, until row state submitted or cancelled.

    Positioning

    • A posição padrão da sobreposição será abaixo da linha que está no modo de edição

    • Se não houver espaço abaixo da linha, a sobreposição aparecerá acima da linha.

    • Uma vez mostrado - superior ou inferior, a sobreposição manterá essa posição durante a rolagem, até que a sobreposição seja fechada.

    Behavior

    • Se a linha estiver no modo de edição, a edição continuará, se uma célula da mesma linha for clicada.

    • Clicar no botão "Concluído" concluirá a edição da linha e enviará alterações para a fonte de dados ou para uma transação, se disponível. Além disso, a linha sairá do modo de edição.

    • Clicar no botão "Cancelar" reverterá todas as alterações atuais na linha e a linha sairá do modo de edição.

    • Se a linha estiver no modo de edição, clicar em uma célula de outra linha concluirá a edição da linha atual e enviará novas alterações de linha (o mesmo comportamento clicando no botão "Concluído"). Se a nova célula que recebe o foco for editável, a nova linha também entrará no modo de edição, enquanto se a célula não for editável, apenas a linha anterior sairá do modo de edição.

    • Se a linha estiver no modo de edição e a Grade for rolada para que a linha saia da área visível, esta ainda estará no modo de edição. Quando a Grade for rolada, para que a linha fique visível novamente, a linha ainda estará no modo de edição. Quando clicado fora da grade, a célula também permanecerá no modo de edição.

    • Ao realizar operações de classificação, filtragem, pesquisa e ocultação, reverterá todas as alterações atuais na linha e a linha sairá do modo de edição.

    • Ao executar operações de paginação, redimensionamento, fixação e movimentação, sairá do modo de edição e enviará o valor mais recente.

    • Cada célula modificada recebe o estilo editado até que a edição da linha seja concluída. Esse é o comportamento quando o Grid não é fornecido com transações. Quando as transações estão disponíveis - o estilo de edição da célula é aplicado até que todas as alterações sejam confirmadas.

    Keyboard Navigation

    • Enter and F2 enters row edit mode

    • Esc exits row edit mode and doesn't submit any of the cell changes, made while the row was in edit mode.

    • Tab move focus from one editable cell in the row to the next and from the right-most editable cell to the CANCEL and DONE buttons. Navigation from DONE button goes to the left-most editable cell within the currently edited row.

    Feature Integration

    • Qualquer operação de alteração de dados encerrará as operações de edição de linha e enviará as alterações de linha atuais. Isso incluirá operações como classificação, alteração de critérios de agrupamento e filtragem, paginação, etc.

    • Os resumos serão atualizados após a conclusão da edição da linha. O mesmo é válido para os outros recursos, como classificação, filtragem, etc.

    • Expandir e recolher linhas agrupadas não encerrará a edição da linha atual.

    Customizing Row Editing Overlay

    Customizing Text

    Customizing the text of the row editing overlay is possible using the igxRowEditTextDirective. The rowChangesCount property is exposed and it holds the count of the changed cells.

    <ng-template igxRowEditText let-rowChangesCount>
     Changes: {{rowChangesCount}}
    </ng-template>
    

    Customizing Buttons

    Customizing the buttons of the row editing overlay is possible using the igxRowEditActionsDirective. If you want the buttons to be part of the keyboard navigation, then each on of them should have the igxRowEditTabStopDirective.

    <ng-template igxRowEditActions let-endRowEdit>
    <button igxButton igxRowEditTabStop (click)="endRowEdit(false)">Cancel</button>
    <button igxButton igxRowEditTabStop (click)="endRowEdit(true)">Apply</button>
    </ng-template>
    

    Estilização

    Using the Ignite UI for Angular Theme Library, we can greatly alter the Row Editing overlay. The Row Editing overlay is a composite element - its UI is comprised of a couple of other components: - igx-banner in order to render its contents - igx-buttons are rendered in the default template (for the Done and Cancel buttons).

    In the below example, we will make use of those two components' styling options, button styling & banner-styling, to customize the experience of our IgxGrid's Row Editing. We will also style the current cell's editor and background to make it more distinct. You can learn more about cell styling in the Cell Styling section.

    Import theme

    The easiest way to style the Row Editing banner is to define styles in our app's global style file (typically styles.scss). The first thing we need to do is import the themes/index file - this gives us access to all the powerful tools of the Ignite UI for Angular Sass framework:

    @use "igniteui-angular/theming" as *;
    
    // IMPORTANT: Prior to Ignite UI for Angular version 13 use:
    // @import '~igniteui-angular/lib/core/styles/themes/index';
    

    Depois de importar o arquivo de temas, podemos criar temas personalizados.

    Defina o tema

    We can now define a custom banner theme that will affect our Row Editing background and make use of one of the predefined palettes namely $purple-palette :

    $banner-theme: banner-theme(
      $banner-background: #e3e3e3,
      $banner-message-color: color($purple-palette, "secondary", 600)
    );
    

    Here we are using my-banner-palette in conjunction with igx-color (exposed by the theme library) for generating our colors.

    Include the theme

    All we have to do now is apply the theme with a Sass @include statement. We pass our newly defined $banner-theme through the css-vars mixin:

    @include css-vars($banner-theme);
    

    Component styles

    Como a sobreposição de edição de linha faz uso de muitos temas de outros componentes, estilizá-la por meio dos estilos globais pode afetar outras partes do nosso aplicativo (por exemplo, banners, botões, etc.). A melhor maneira de evitar isso é definir o escopo do tema do banner para o arquivo de estilo do componente específico ao qual ele é aplicado.

    Note

    If the component is using an Emulated ViewEncapsulation, it is necessary to penetrate this encapsulation using ::ng-deep in order to style the grid Row Editing Overlay.

    // custom.component.scss
    
    :host {
      ::ng-deep {
        @include css-vars($banner-theme);
      }
    }
    

    Com a sintaxe acima, nosso tema de banner personalizado se aplica corretamente à sobreposição de edição de linha da grade.

    Custom Templates

    To further customize our Row Editing overlay, we can pass a custom template so we can style the Done and Cancel buttons separately:

    <!-- in component.html -->
    <igx-grid>
        <ng-template igxRowEditActions let-endRowEdit>
            <div class="custom-buttons">
                <button igxIconButton="flat" class="custom-button" igxRowEditTabStop (click)="endRowEdit(false)">
                    <igx-icon>clear</igx-icon>
                </button>
                <button igxIconButton="flat" class="custom-button" igxRowEditTabStop (click)="endRowEdit(true)">
                    <igx-icon>check</igx-icon>
                </button>
            </div>
        </ng-template>
    </igx-grid>
    

    After we've defined our custom buttons, we can make use of the button-theme to style them. You can learn more about igx-button styling in the Button Styling documentation. We can create a custom theme for our Done and Cancel:

    // custom.component.scss
    ...
    
    $button-theme: button-theme(
      $palette: $purple-palette
    );
    
    ...
    .custom-buttons {
      @include css-vars($button-theme);
    }
    

    We scope our @include statement in .custom-buttons so that it is only applied to the Doneand Cancel buttons.

    Demo

    Depois de estilizar o banner e os botões, também definimos um estilo personalizado para a célula no modo de edição. O resultado de todos os estilos combinados pode ser visto abaixo:

    Note

    A amostra não será afetada pelo tema global selecionado deChange Theme.

    Known Issues and Limitations

    • Quando a grade nãoprimaryKey tem um set definido e cenários de dados remotos são ativados (ao paginar, ordenar, filtrar, rolar requisições de gatilho para um servidor remoto para recuperar os dados a serem exibidos na grade), uma linha perderá o seguinte estado após a conclusão de uma solicitação de dados:
      • 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.