Search code examples
javascriptjqueryangularangular7

How to change color of row that contains different value using Angular 7?


How can I give a red color to a row that has a different value by using Angular 7?

I have tried to give a red color to the row in the HTML table that has different values on the same row. If each td on same row has different values from each cell behind it will give the row a red font color. I tried that by using jQuery and it run successfully, but I cannot do that using Angular 7. How can I do it?

$(document).ready(function() {
  MakeColorForDifferentContent();
});

function MakeColorForDifferentContent() {
  $("table tr").each((_, tr) => {
    var tempValue = $($(tr).find('td:first-child')).text();
    var tds = $(tr).find('td:not(:first-child)');
    var isDiff = false;
    
    tds.each((_, td) => {
      if ($(td).text() !== tempValue) {
        isDiff = true;
        return true;
      }
    });

    if (isDiff)
      $(tr).css('color', 'red');
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
  <col width="500">
  <col width="500">
  <col width="500">
  <col width="500">
  <tr bgcolor="#6699FF" width="100%">
    <th>Part1</th>
    <th>Part2</th>
    <th>Part3</th>
    <th>Part4</th>
    <tr>
      <td>12</td>
      <td>12</td>
      <td>12</td>
      <td>12</td>
    </tr>
    <tr>
      <td>12</td>
      <td>15</td>
      <td>12</td>
      <td>12</td>
    </tr>
    <tr>
      <td>17</td>
      <td>15</td>
      <td>12</td>
      <td>12</td>
    </tr>
</table>


Solution

    1. Don't use jQuery with Angular (at least for DOM manipulation)
    2. The way to do conditional styling in Angular is with the class directive

    This is a rough demonstration of the techniques you should be familiar with for doing this kind of task:

    <table>
    <tr *ngFor="let row of rows" [class.red-row]="isDiff(row)">
    <td *ngFor="let cell of row">{{cell}}</td>
    </tr>
    </table>
    

    In your typescript:

    rows: number[][];
    
    ngOnInit(): void {
      this.rows = [
        [12, 12, 12, 12],
        [12, 15, 12, 12]
      ];
    }
    
    isDiff(row: number[]): boolean {
      const tempValue: number = row[0];
      for (let i = 1; i < row.length; i++) {
        if (tempValue !== row[i]) {
          return true;
        }
      }
      return false;
    }
    

    In your style sheet:

    .red-row {
      color: red;
    }