You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在运行时根据ag-grid详情字段值设置详情行颜色

Solution for Dynamic Styling of ag-grid Detail Rows

Here's a step-by-step implementation to dynamically highlight detail rows based on fetched backend data:

1. Component Setup

Add necessary properties to your component to track matched keys and grid references:

import { GridApi, DetailGridParams, CellClassParams } from 'ag-grid-community';
import { ConfigDto, KeyObject } from './your-interfaces';

export class YourComponent {
  // Store matched keys (using Set for O(1) existence checks)
  private matchedKeysSet: Set<string> = new Set();
  // Reference to main grid API
  private mainGridApi: GridApi | undefined;
  // Your main grid options
  mainGridOptions: GridOptions = {};

  // ... rest of your component code
}

2. Configure Main Grid with Master-Detail

Set up the main grid to render detail rows, and define the detail grid's column definitions with dynamic styling:

ngOnInit() { // or your component initialization method
  this.mainGridOptions = {
    columnDefs: [
      { field: 'name', headerName: 'Config Name' },
      // Add other main row columns as needed
    ],
    masterDetail: true,
    detailRowHeight: 200,
    // Define detail grid options dynamically
    detailGridOptions: (params: DetailGridParams<ConfigDto>) => ({
      columnDefs: [
        {
          field: 'key',
          headerName: 'Key',
          // Dynamic cell class based on matched keys
          cellClass: (cellParams: CellClassParams<KeyObject>) => {
            // Adjust the identifier based on your equality logic (key only, or key+value)
            const identifier = `${cellParams.data.key}-${cellParams.data.value}`;
            return this.matchedKeysSet.has(identifier) ? 'matched-row' : '';
          }
        },
        { field: 'value', headerName: 'Value' }
      ],
      rowData: params.data.keys || []
    }),
    // Handle row selection change
    selectionChanged: this.onSelectionChanged.bind(this),
    onGridReady: (params) => {
      this.mainGridApi = params.api;
    }
  };
}

3. Handle Selection and Fetch Data

Implement the selectionChanged method to fetch backend data and refresh the detail grid:

async onSelectionChanged() {
  const selectedRows = this.mainGridApi?.getSelectedRows<ConfigDto>() || [];
  
  // Clear matched keys if no row is selected
  if (selectedRows.length === 0) {
    this.matchedKeysSet.clear();
    return;
  }

  const selectedConfig = selectedRows[0];
  
  try {
    // Fetch matched KeyObject list from your backend service
    const fetchedKeys: KeyObject[] = await this.yourBackendService.getMatchedKeys(selectedConfig.name);
    
    // Populate the Set with unique identifiers for quick lookup
    this.matchedKeysSet = new Set(
      fetchedKeys.map(k => `${k.key}-${k.value}`)
    );

    // Refresh the detail grid to apply new styles
    const selectedRowNode = this.mainGridApi?.getSelectedNodes()[0];
    if (selectedRowNode?.detailNode) {
      selectedRowNode.detailNode.api.refreshCells({ force: true });
    }
  } catch (error) {
    // Handle fetch error (e.g., clear matched keys, show error message)
    this.matchedKeysSet.clear();
    console.error('Failed to fetch matched keys:', error);
  }
}

4. Add CSS for Highlighting

Define the CSS class to style matched detail rows:

.matched-row {
  background-color: #d4edda; /* Light green background */
  color: #155724; /* Dark green text for contrast */
}

Key Notes

  • Equality Logic: Adjust the identifier (e.g., ${key}-${value}) based on how you define a "matching" KeyObject. If only the key matters, use just cellParams.data.key.
  • Performance: Using a Set ensures fast existence checks, which is crucial if dealing with large lists.
  • Multiple Selection: If allowing multiple row selection, track matched keys per row using a Map<string, Set<string>> where the key is the main row's unique ID.

内容的提问来源于stack exchange,提问作者NobiliChili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:06:19