update header color on cell edit in table

138 Views Asked by At

I am using prime ng cell edit. My code is as follows.

<p-table [value]="products" dataKey="id" [tableStyle]="{ 'min-width': '50rem' }">
    <ng-template pTemplate="header">
        <tr>
            <th style="width:25%">Code</th>
            <th style="width:25%">Name</th>
            <th style="width:25%">Inventory Status</th>
            <th style="width:25%">Price</th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-product let-editing="editing">
        <tr>
            <td [pEditableColumn]="product.code" pEditableColumnField="code">
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="product.code" />
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{ product.code }}
                    </ng-template>
                </p-cellEditor>
            </td>
            <td [pEditableColumn]="product.name" pEditableColumnField="name">
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="product.name" required />
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{ product.name }}
                    </ng-template>
                </p-cellEditor>
            </td>
            <td [pEditableColumn]="product.inventoryStatus" pEditableColumnField="inventoryStatus">
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText [(ngModel)]="product.inventoryStatus" />
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{ product.inventoryStatus }}
                    </ng-template>
                </p-cellEditor>
            </td>
            <td [pEditableColumn]="product.price" pEditableColumnField="price">
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="product.price" />
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{ product.price | currency: 'USD' }}
                    </ng-template>
                </p-cellEditor>
            </td>
        </tr>
    </ng-template>
</p-table>

TS:

import { Component, OnInit } from '@angular/core';
import { Product } from '../../domain/product';
import { ProductService } from '../../service/productservice';

@Component({
    selector: 'table-cell-edit-demo',
    templateUrl: 'table-cell-edit-demo.html'
})
export class TableCellEditDemo implements OnInit {
    products!: Product[];

    constructor(private productService: ProductService) {}

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

Stackblitz :

https://stackblitz.com/run?file=src%2Fapp%2Fapp.component.html

Cell edit is working fine. I just want to highlight that particular header and row with red background color which is getting edited currently. How can I do that?

1

There are 1 best solutions below

0
Mouayad_Al On

in order to colorize the row when edit a cell: 1- Add a template reference variable #rows to the <tr> element inside the pTemplate="body" to read the rows using @ViewChildren. This will allow you to access the rows in your component.

<tr #rows>

2- Add a template reference variable #tableHeader to the <tr> element inside the pTemplate="header" to read the row using @ViewChild. This will allow you to access the header row in your component.

   <tr #tableHeader>
       <th id='code'>Code</th>
       <th id='name'>Name</th>
       <th id='category'>Category</th>
       <th id='quantity'>Quantity</th>
    </tr>

3- Modify the <th> elements where you want to track edits by adding an [id] attribute.set Id for example: [id]="'name'". name of the th field.

4- Inside the <input> element that represents the editable field, add (ngModelChange) to listen for changes in the input value. When the value changes, call a method such as colorizeRow(rowIndex, headerId) and pass the rowIndex and headerId as parameters.

<input pInputText type="text" [(ngModel)]="product.name" (ngModelChange)="colorizeRow(ri,'name')" required />

Don't forget to add let-ri="rowIndex" on <ng-tempalte pTemplate="body">

5-Add an @ViewChildren decorator to your component class to read the rows using the template reference variable #rows:

@ViewChildren('rows') rows: QueryList<ElementRef<HTMLTableRowElement>>;

6-Add an @ViewChild decorator to your component class to read the header row using the template reference variable #tableHeader:

@ViewChild('tableHeader') tableHeader: ElementRef<HTMLTableRowElement>;

7-Inject the Renderer2 into your component's constructor to use it for manipulating the DOM:

constructor(private _renderer2: Renderer2) {}

8-Define the colorizeRow function in your component to set the background color of the edited row and header. This function takes the rowIndex and headerId as parameters.

  colorizeRow(rowIndex: number, headerId: string) {
  // Retrieve the native element corresponding to the row at the given rowIndex
  const row = this.rows.get(rowIndex).nativeElement;
  
  // Set the background color of the row to '#ececec'
  this._renderer2.setStyle(row, 'backgroundColor', '#ececec');
  
  // Retrieve the cells of the table header
  const cells = this.tableHeader.nativeElement.cells;
  
  // Iterate over the cells in the table header
  for (let index = 0; index < cells.length; index++) {
    // Retrieve the current cell
    const cell = cells.item(index);
    
    // Check if the id property of the current cell matches the headerId
    if (cell.id == headerId) {
      // If there is a match, set the background color of the cell to '#ececec'
      this._renderer2.setStyle(cell, 'backgroundColor', '#ececec');
      
      // Break out of the loop since the desired cell has been found and colored
      break;
    }
  }
}