0
votes

Ok, I need to set some style rules like background-color for the whole row (for Ag-grid ), depends on some data which haven't to display or be in the table. Also, there is a lot of data in the table which is sorted and real-time updated. Which way to do it is better?

I use Angular 6 and ag-grid ^17.1.1 in my project.

Because of style for row depends on a certain value, I add this value to the table and set hide flag to true. Then I just set getRowStyle function in gridOptions.

getRowStyle: (params) => {
  if (params.data.type === 'car' && params.data.value === 'audi') {
    return { 'background-color': 'green' };
  }
  if (params.data.type === 'car' && params.data.value === 'ford') {
    return { 'background-color': 'blue' };
  }
}

Maybe, is there a better way to do it?

1
You may want to consider using a CSS class to encapsulate the styles and toggle the classes based on data. I don't know if ag-grid makes that easy or hard though.Heretic Monkey

1 Answers

1
votes

for working with ag-Grid, my suggestion is to set the class for the row and have that class be the one that is applying any styles you need for each case. I am suggesting going with class rather than direct styles because it is cleaner and faster (see here Inline Styles vs Classes)

the way to do this I think is shown here in ag-Grid documentation https://www.ag-grid.com/javascript-grid-row-styles/#row-class-rules

and specifically I think that this example is the cleanest and most direct.

gridOptions.rowClassRules: {
  // apply green to 2008
  'rag-green-outer': function(params) { return params.data.year === 2008},

  // apply amber 2004
  'rag-amber-outer': function(params) { return params.data.year === 2004},

  // apply red to 2000
  'rag-red-outer': function(params) { return params.data.year === 2000}
}

OR the shorthand version

gridOptions.rowClassRules: {
    'rag-green': 'data.age < 20',
    'rag-amber': 'data.age >= 20 && data.age < 25',
    'rag-red': 'data.age >= 25'
}

Original Answer

direct answer is to bind to [ngStyle] like the example here that I lifted directly from angular.io here https://angular.io/guide/template-syntax#ngStyle

<div [ngStyle]="currentStyles">
  This div is initially italic, normal weight, and extra large (24px).
</div>
  this.currentStyles = {
    'font-style':  this.canSave      ? 'italic' : 'normal',
    'font-weight': !this.isUnchanged ? 'bold'   : 'normal',
    'font-size':   this.isSpecial    ? '24px'   : '12px'
  };

but I would also suggest that you try out style binding, which is using the template syntax to set styles dynamically based on content.

<div [style.background-color]="isFordCar(data) ? 'blue' : 'green'" >
</div>

OR better yet, why not use a class, which is ultimately cleaner and shares the same kind of binding syntax

<div [class.ford]="isFordCar(data)" >
</div>