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 Answers1

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567