简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM