Looking to enhance functionality by dynamically adding and removing the 'active' class to 'li a' elements on click. While the current code performs well when clicking from top to bottom, it fails to work in reverse order.
- component.html
<div class="container text-center">
<ul id="myList" class="pt-5">
<li class="p-3">
<a href="#" class="d-inline-block" (click)="linkActive($event)">List 1</a>
</li>
<li class="p-3">
<a href="#" class="d-inline-block" (click)="linkActive($event)">List 2</a>
</li>
</ul>
</div>
- component.ts
linkActive(event) {
const activeClass = event.srcElement.classList.contains('active');
const classFound = document.querySelector('li a');
const hpn = classFound.classList.contains('active');
if (activeClass == true) {
if (hpn == true) {
classFound.classList.remove('active');
}
alert('true');
event.srcElement.classList.remove('active');
} else {
if (hpn == true) {
classFound.classList.remove('active');
}
alert('false');
event.srcElement.classList.add('active');
}
}
To see the code in action, visit: https://stackblitz.com/edit/angular-ivy-jf9xvp