[Fixed] Validation of HTML table cell and changing background color using Javascript

Issue

This is HTML table and I want to validate it in such a way that if user clears entry, the background color of particular cell should be turned red. Code for model should be in JavaScript or Typescript. Please don’t provide jQuery solutions

app.component.html

  <table class="material-table">
    <thead>
      <tr>
        <th></th>
        <!-- <th *ngFor="let schema of tableSchema">
          {{ schema.field }}
        </th> -->
      </tr>
    </thead>
    <tr *ngFor="let rowData of tableData">
      <td value="Delete" (click)="deleteRow(rowData)">X</td>
      <td
        *ngFor="let schema of tableSchema"
        [class.red-text]="!rowData[schema.field].valid"
      >
        <span
          #el
          contenteditable
          (blur)="rowData[schema.field].value = el.innerText"
          
        >
          {{ rowData[schema.field].value }}
        </span>
      </td>
    </tr>
  </table>

Solution

Use NgClass.

<td *ngFor="let schema of tableSchema" [ngClass]="{'red-text':!rowData[schema.field].valid}">
    <span #el contenteditable (blur)="rowData[schema.field].value = el.innerText">
        {{ rowData[schema.field].value }}
    </span>
</td>

Leave a Reply

(*) Required, Your email will not be published