1

I have a list of items and when the page loads I want the first item to look active.

<li *ngFor="let link of links; let i = index;" (click)="setActive(i)" class="{i === activeIndex ? 'active' : ''}">
    <a routerLink="{{link.url}}">{{link.text}}</a>
</li>

and the class looks like this

export class NavbarComponent{
    private links: Array<Object>;
    private activeIndex: number = 0;

    constructor(private linksService: LinksService) {
        this.links = linksService.getNavLinks();
    }

    setActive(index: number) {
        this.activeIndex = index;
    }
}

The list item becomes active correctly on clicking it. But not when the page loads. What mistake am I making?

1 Answer 1

2

You can use the first variable provided by ngFor and use [class.xxx]="..." binding to set/remove a class:

<li *ngFor="let link of links; let i = index" 
     [class.active]="activeIndex == i" 
     (click)="setActive(i)">
    <a routerLink="{{link.url}}">{{link.text}}</a>
</li>

See also Implementing ngClassEven ngClassOdd for angular 2

Sign up to request clarification or add additional context in comments.

3 Comments

@micronyks if you remove {{}} you need to add at least []. When link.url returns a string (not an array) then {{}} is fine as well.
Thanks, it works, but now it messes up my setActive function and it stays always active. Can you please guide me on changing this function?
I see. In this case you can't use first. I updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.