Angular 2 - 根据组件变量设置列表项的属性

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

我有一个项目列表,当页面加载时,我希望第一个项目看起来处于活动状态。

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

class 看起来像这样

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;
    }
}

列表项在单击时正确激活。但不是在页面加载时。我犯了什么错误?

您可以使用 ngFor 提供的 first 变量并使用 [class.xxx]="..." 绑定到 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>

另见