简体   繁体   English

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

[英]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: 您可以使用ngFor提供的first变量,并使用[class.xxx]="..."绑定来设置/删除类:

<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 另请参见实现angular 2的ngClassEven ngClassOdd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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