Search code examples
ag-gridag-grid-vuedatagridviewcellstyle

ag-grid: highlight duplicated cell values


I am using ag-grid and I would like to highlight cells in a column if the cell values for a particular column are duplicated. The duplicated cells should be highlighted using a red border.


Solution

  • You can achieve the duplicate highlighting by iterating through the row data to detect the duplicate values and then pass the detected duplicates to a custom cellStyle function.

      defaultColDef = {
        cellStyle: function(params) {
            const columnId = params.colDef.field;
            const currentValue = params.value;
            const duplicates = params.context.duplicates;
    
            if (columnId in duplicates && duplicates[columnId] == currentValue){
              return { 'background-color': 'red' };
            }
      
            return { 'background-color': null};
          }
      }
    
      ngOnInit() {
        for (let key in this.rowData[0]) {
          let seenValues = new Set<string>()
          for (let i in this.rowData){
            const item = this.rowData[i]
            if (seenValues.has(item[key])){
              this.duplicates[key] = item[key];
            } else {
              seenValues.add(item[key]);
            }
          }
        }  
      }
    

    Here is an example:

    Image of ag-grid highlighting duplicate values

    Here is the code for AngularJS: https://stackblitz.com/edit/ag-grid-duplicates-highlighting-6adsz6

    Here is the code for Vue: https://stackblitz.com/edit/ag-grid-highlight-duplicates-vue