Trying to implement a sorting function in my table by clicking on the column header has proven to be challenging. The desired behavior is that on the first click, items in the column should be sorted in ascending order, and on the second click, they should be sorted in descending order.
Below is the HTML code snippet:
<thead>
<tr>
<th (click)="sorting('FirstName')" class="sorting" role="columnheader" tabindex="0" aria-controls="sample_1" rowspan="1" colspan="1" aria-label="Ime i prezime : activate to sort column ascending">
First Name
</th>
<th (click)="sorting('Email')" class="sorting" role="columnheader" tabindex="0" aria-controls="sample_1" rowspan="1" colspan="1" aria-label="Email : activate to sort column ascending">
Email
</th>
<th (click)="sorting('Username')" class="sorting" role="columnheader" tabindex="0" aria-controls="sample_1" rowspan="1" colspan="1" aria-label="Username: activate to sort column ascending">
Username
</th>
<th>
Actions
</th>
</tr>
</thead>
And here is the corresponding TypeScript code:
sorting(sortBy) {
this.sortBy = sortBy;
let tableHeaderItems = Array.from(document.querySelectorAll('.sorting'));
const handleClick = (e) => {
e.preventDefault();
e.stopPropagation();
console.log(e.currentTarget.classList);
if (e.currentTarget.classList.contains('sorting_asc')) {
e.currentTarget.classList.remove('sorting_asc');
e.currentTarget.classList.add('sorting_desc');
this.sortDirection = "desc";
}
else if (e.currentTarget.classList.contains('sorting_desc')) {
e.currentTarget.classList.remove('sorting_desc');
e.currentTarget.classList.add('sorting_asc');
this.sortDirection = "asc";
}
else {
tableHeaderItems.forEach(node => {
node.classList.remove('sorting_asc');
node.classList.remove('sorting_desc');
});
e.currentTarget.classList.add('sorting_asc');
this.sortDirection = "asc";
}
}
tableHeaderItems.forEach(node => {
node.addEventListener('click', handleClick)
});
this.service.getAll(this.sortBy, this.sortDirection);
}
Encountering a problem where the function is only triggered once with each click, but const handleClick
is being called multiple times. Initially, clicking on the column does not trigger anything inside const handleClick
. Subsequent clicks result in inconsistent behavior - the function is called twice, three times, or more depending on the number of clicks. Any insights into why this might be happening would be greatly appreciated.