A web app (Angular SPA) displays a large table but it does not allow sorting so I'm trying to do it via the console. I've got the sorting part but re-inserting the rows causes it to lose reactivity (listeners) which is pointless.
function sortRows() {
const table = document.querySelector('#mytable');
const tbody = table.querySelector('tbody');
const rows = tbody.querySelectorAll('tr');
const rowsSortedBySize = Array.from(rows).sort((a, b) => {
return Number(b.children[3].textContent) - Number(a.children[3].textContent);
});
// remove rows
tbody.innerHTML = "";
// add sorted rows
rowsSortedBySize.forEach(row => tbody.appendChild(row));
}
<table id="mytable">
<tbody>
<tr>
<td><input type="checkbox" name="one"></td>
<td>name</td>
<td>description</td>
<td>1</td>
<td>date</td>
</tr>
<tr>
<td><input type="checkbox" name="two"></td>
<td>name</td>
<td>description</td>
<td>2</td>
<td>date</td>
</tr>
</tbody>
</table>
<button onclick="sortRows()">Sort Rows</button>
How can I sort without re-inserting to avoid losing reactivity?
You are not using Angular in the correct way.
I will show you a different solution for your problem, but you need to make a lot of changes.
First, create an array in your .ts file. It has to be an array of objects, containing this data:
<td><input type="checkbox" name="one"></td>
<td>name</td>
<td>description</td>
<td>1</td>
<td>date</td>
So.
public myData = [
{
name: 'name 1', // name field
description: 'description 1', // description field
itemNumber: 1,
date: new Date(),
selected: true
},
{
name: 'name 2',
description: 'description 2',
itemNumber: 2,
date: new Date(),
selected: false
}]
Then, on your .html file
<table id="mytable">
<tbody>
<tr *ngFor="let item of myData; let i = index">
<td>
<input type="checkbox" [checked]="item.selected" (change)="item.selected = !item.selected">
</td>
<td>{{ item.name }}</td>
<td> {{ item.description }} </td>
<td> {{ item.itemNumber }} </td>
<td> {{ item.date }} </td>
</tr>
</tbody>
</table>
<button (click)="sortRows()">Sort Rows</button>
So now your method would be something like this:
public sortRows(): void {
this.myData = this.myData.sort((a, b) => b.itemNumber - a.itemNumber);
}