I want to add the class name 'active' onClick to 'li a' & also remove any 'active' class present on the 'li a'. The current code is working properly if I click sequence from top elements, but when I click elements from bottom to top, it's not working.
<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>
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');
}
}
Please find the sample code : https://stackblitz.com/edit/angular-ivy-jf9xvp
Do not manipulate the DOM directly like this, You can use ngClass to achieve the desired result:
template:
<a href="#" class="d-inline-block" [ngClass]="{'active': activeList === 1}" (click)="linkActive(1)">List1</a>
.ts
public activeList: number;
...
public linkActive(listNumber: number) {
this.activeList = listNumber;
}
In general, as recommended in comments, do the heroes tutorial and try to understand how to use typescript.