Angular Fijación de filas de cuadrícula

    One or multiple rows can be pinned to the top or bottom of the Angular UI Grid. Row Pinning in Ignite UI for Angular allows end-users to pin rows in a particular order, duplicating them in a special area that is always visible even when they scroll the Grid vertically. The Material UI Grid has a built-in row pinning UI, which is enabled by initializing an igxActionStrip component in the context of Grid. In addition, you can define custom UI and change the pin state of the rows via the Row Pinning API.

    Angular Grid Row Pinning Example

    Row Pinning UI

    The built-in row pinning UI is enabled by adding an igxActionStrip component with the GridPinningActions component. The action strip is automatically shown when hovering a row and will display a pin or unpin button icon based on the state of the row it is shown for. An additional action allowing to scroll the copy of the pinned row into view is shown for each pinned row as well.

    <igx-grid [data]="data" [autoGenerate]="false">
        <igx-column *ngFor="let c of columns" [field]="c.field" [header]="c.field">
        </igx-column>
    
        <igx-action-strip #actionStrip>
            <igx-grid-pinning-actions></igx-grid-pinning-actions>
            <igx-grid-editing-actions></igx-grid-editing-actions>
        </igx-action-strip>
    </igx-grid>
    

    Row Pinning API

    Row pinning is controlled through the pinned input of the row. Pinned rows are rendered at the top of the Grid by default and stay fixed through vertical scrolling of the unpinned rows in the Grid body.

    this.grid.getRowByIndex(0).pinned = true;
    

    You may also use the Grid's pinRow or unpinRow methods of the IgxGridComponent to pin or unpin records by their ID:

    this.grid.pinRow('ALFKI');
    this.grid.unpinRow('ALFKI');
    

    Note that the row ID is the primary key value, defined by the primaryKey of the grid, or the record instance itself. Both methods return a boolean value indicating whether their respective operation is successful or not. Usually the reason they fail is that the row is already in the desired state.

    A row is pinned below the last pinned row. Changing the order of the pinned rows can be done by subscribing to the rowPinning event and changing the insertAtIndex property of the event arguments to the desired position index.

    <igx-grid #grid1 [data]="data" [autoGenerate]="true" (rowPinning)="rowPinning($event)">
    </igx-grid>
    
    public rowPinning(event) {
        event.insertAtIndex = 0;
    }
    

    Pinning Position

    You can change the row pinning position via the pinning configuration option. It allows you to set the pin area position to either Top or Bottom. When set to Bottom pinned rows are rendered at the bottom of the grid, after the unpinned rows. Unpinned rows can be scrolled vertically, while the pinned rows remain fixed at the bottom.

    <igx-grid [data]="data" [autoGenerate]="true" [pinning]="pinningConfig"></igx-grid>
    
    public pinningConfig: IPinningConfig = { rows: RowPinningPosition.Bottom };
    

    Custom Row Pinning UI

    Puede definir su interfaz de usuario personalizada y cambiar el estado del pin de las filas a través de la API relacionada.

    Via extra column with icon

    Digamos que en lugar de una franja de acción le gustaría mostrar un ícono de pin en cada fila, permitiendo al usuario final hacer clic y cambiar el estado del pin de una fila en particular. Esto se puede hacer agregando una columna adicional con una plantilla de celda que contenga el ícono personalizado.

    <igx-grid [data]="data" [primaryKey]="'ID'" [autoGenerate]="false">
        <igx-column width="70px">
            <ng-template igxCell let-cell="cell" let-val>
                <igx-icon class="pin-icon" (mousedown)="togglePinning(cell.row, $event)">
                    {{cell.row.pinned ? 'lock' : 'lock_open'}}
                </igx-icon>
            </ng-template>
        </igx-column>
        <igx-column *ngFor="let c of columns" [field]="c.field" [header]="c.field">
        </igx-column>
    </igx-grid>
    

    Al hacer clic en el icono personalizado, el estado del pin de la fila relacionada se puede cambiar utilizando los métodos API de la fila.

    public togglePinning(row: IgxGridRow, event) {
        event.preventDefault();
        if (row.pinned) {
            row.unpin();
        } else {
            row.pin();
        }
    }
    

    Manifestación

    Via row drag

    Supongamos que desea poder arrastrar y soltar directamente una fila entre las filas fijadas y no fijadas para cambiar su estado de fijación. Esto se puede lograr habilitando la función de arrastre de filas y fijando/desanclando las filas a través de la API al soltarlas.

    First, the grid should be marked as a drop area using the igxDrop directive and the row drag functionality should be enabled via the rowDraggable option.

    <igx-grid [data]="data" [autoGenerate]="true" [rowDraggable]="true"
        [primaryKey]="'ID'" igxDrop (dropped)="onDropAllowed($event)">
    </igx-grid>
    

    Then the dropped event can be used to handle the reorder and pin/unpin logic.

    public onDropAllowed(args) {
        const event = args.originalEvent;
        let currRowPinnedIndex;
        const currRowIndex = this.getCurrentRowIndex(this.grid.rowList.toArray(),
            { x: event.clientX, y: event.clientY });
        if (currRowIndex === -1) { return; }
    
        const currRowID = this.getCurrentRowID(this.grid.rowList.toArray(),
            { x: event.clientX, y: event.clientY });
    
        const currentRow = this.grid.rowList.toArray().find((r) => r.rowID === currRowID);
        if (currentRow.pinned) {
            currRowPinnedIndex = this.grid.pinnedRows.indexOf(this.grid.pinnedRows.find((r) => r.rowID === currRowID));
        }
        // remove the row that was dragged and place it onto its new location
        this.grid.deleteRow(args.dragData.key);
        this.data.splice(currRowIndex, 0, args.dragData.data);
        if (currentRow.pinned && !args.dragData.pinned) {
            this.grid.pinRow(args.dragData.key, currRowPinnedIndex);
        } else if (!currentRow.pinned && args.dragData.pinned) {
            this.grid.unpinRow(args.dragData.key);
        } else if (currentRow.pinned && args.dragData.pinned) {
            this.grid.unpinRow(args.dragData.key);
            this.grid.pinRow(args.dragData.key, currRowPinnedIndex);
        }
    }
    

    Esto permitiría reordenar las filas y moverlas entre las colecciones de filas fijadas y no fijadas.

    Manifestación

    Row Pinning Limitations

    • Solo se pueden anclar registros que existen en la fuente de datos.
    • El estado de fijación de filas no se exporta a Excel. La cuadrícula se exporta como si no se hubiera aplicado ninguna fijación de filas.
    • Debido a cómo se almacenan internamente las filas fijadas para que puedan aparecer tanto en las áreas fijadas como en las áreas no fijadas de la cuadrícula, la fijación de filas no se admite cuando los registros de la cuadrícula se obtienen desde un punto final remoto a pedido (virtualización remota).
    • Las copias de filas fijadas en el área desplazable de la cuadrícula son una parte integral de cómo otras características de la cuadrícula logran su funcionalidad en presencia de filas fijadas y, por lo tanto, su creación no se puede deshabilitar ni eliminar.
    • Como la selección de filas funciona completamente con ID de fila, al seleccionar filas fijadas también se seleccionan sus copias (y viceversa). Además, la selección de rango (por ejemplo, usando Shift + clic) dentro del área fijada funciona de la misma manera que seleccionar un rango de filas dentro del área desplazable. La selección resultante incluye todas las filas intermedias incluso si no están fijadas actualmente. Obtener las filas seleccionadas a través de la API solo devuelve una única instancia de cada registro seleccionado.
    • 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:
      • Selección de fila
      • Fila Expandir/contraer
      • Edición de filas
      • Fijación de filas

    Estilismo

    The IgxGrid allows styling through the Ignite UI for Angular Theme Library. The Grid's grid-theme exposes a wide variety of properties, which allow the customization of all the features of the Grid.

    A continuación, veremos los pasos para personalizar el estilo de fijación de filas de la cuadrícula.

    Importing the Styling Library

    To begin the customization of the row pinning feature, you need to import the index file, where all styling functions and mixins are located.

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

    Defining a Theme

    Next, create a new theme, that extends the grid-theme and accepts the parameters, required to customize the row pinning feature as desired.

    $custom-grid-theme: grid-theme(
      $pinned-border-width: 5px,
      $pinned-border-style: double,
      $pinned-border-color: #ffcd0f,
      $cell-active-border-color: #ffcd0f
    );
    

    Using CSS variables

    El último paso es pasar el tema de cuadrícula personalizado:

    @include css-vars($custom-grid-theme);
    

    Manifestación

    Note

    The sample will not be affected by the selected global theme from Change Theme.

    API References

    Additional Resources

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.