I’m working on a p-table to see if duplicate entries are present in a table, and if present turn them to a red background. On the initial loading of the page the p-table properly applies the styling and highlights duplicates red, however, when I click to page 2 or further they don’t have any styling added. Also, if I click back to page 1 the styling has been removed. I’m assuming it’s something to do with the amount of elements being rendered in on load vs not rendered but I’m not sure how to detect and update the stylings of pages. I’m tweaking my code based of an answer provided on the question How can I change a color of row by index by Utku Albayrak.
For my CSS I have the following styling:
:host ::ng-deep .not-valid{
background-color: rgba(185, 24, 24, 0.15) !important
}
In my TS class I have used ngAfterViewInit to call my function on page load as ngInit would be called before table would be rendered in HTML and gave an error about classList.
ngAfterViewInit(){
this.checkWriteValue();
}
arrayData: String[] = ["Matt", "David", "Matt", "Smith"];
checkWriteValue(){
for(let i = 0; i < this.arrayData.length; i++){
let tableRow = HTMLElement = document.getElementById('tableRow' + i)
for(let j = 0; j < this.arrayData.length; j++){
let rowVal = this.arrayData[j]
if(i !== j){
if(this.arrayData.includes(rowVal)){
tableRow.classList.add('not-valid');
}
}
}
}
}
My HTML:
<p-table styleClass="p-datatable-gridlines" [value]="arrayData" [paginator]="true" [rows]="2" [showCurrentPageReport]="true">
<ng-template pTemplate="header">
<tr>
<th>Name</th>
</ng-template>
<ng-template pTemplate="body" let-carrier let=i="rowIndex">
<tr [id] = "'tableRow' + i">
<td>{{ carrier }}</td>
</tr>
</ng-template>
</p-table>