krsna
krsna

Reputation: 4353

How to apply active class to anchor links in a horizontal menu in SCSS

I'm trying to achieve toggle functionality between several anchor links in a horizontal menu. The problem I'm facing currently is, the active class is not being applied to links.

What I was expecting is, when user clicks on the link, the color of the text should change. Only the selected link text color should change.

SCSS

.link-active{
    &:active,
    &:hover {
        color: red;
    }
}

HTML

<div class="horizontal-scroll">
    <span *ngFor="let menuOption of homePageMenu; let i = index;">
        <a class="menu-chip"
        [ngClass]="{'link-active': isActive}"
        (click)="handleMenuItemClick(i)">{{menuOption.name}}</a>
    </span>
</div>

I created a working example using StackBlitz. Could anyone please guide.

Upvotes: 0

Views: 1088

Answers (2)

Lex Caraig
Lex Caraig

Reputation: 1

you could just use a [routerLinkActive]="your-active-class" directive in an anchor tag and it will automatically toggle the classes for you.

Upvotes: 0

djay1988
djay1988

Reputation: 107

I have edited your code in StackBlitz. check it out https://stackblitz.com/edit/anchor-menu-toggle-9vfa8i

Edited

I have change the followings

  1. in the ts file isActive = false; to activeIndex = false; to get the current activated index
  2. In the toggle function change to get the clicked index and assign to the activeIndex
  3. in SCSS
    &:active to &.active , I used active as a class, not pseudo state
  4. In the html [class.active]="activeIndex==i" added because when activeIndex equels to loop index the active class will add to the element

I hope this will clear every thing.

Upvotes: 1

Related Questions