Search code examples
angularangular2-directivesangular2-components

Angular 2 - set attribute of list item according to component variable


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?


Solution

  • 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