Angular2 - 将CSS类添加到选定元素

时间:2016-10-18 18:25:39

标签: html css angular typescript angular2-directives

我的.html中有以下代码:

<ul id="navbar-example" class="nav nav-pills nav-stacked" *ngFor="let object of objects; let i = index;">
    <li class="nav-item" *ngIf = "i==0">
        <a id="{{object.code}}" class="nav-link active" (click)="clicked(object)">{{object.name}}</a>
    </li>
    <li class="nav-item" *ngIf = "i!=0">
        <a id="{{object.code}}" class="nav-link" (click)="clicked(object)">{{object.name}}</a>
    </li>
</ul>

因此加载ul时第一个元素处于活动状态。现在,我想将active类添加到选定的<a></a>并切换具有active的类。我怎样才能实现它?

编辑:

我简化为:

<ul id="navbar-example" class="nav nav-pills nav-stacked" *ngFor="let object of objects;">
    <li class="nav-item" >
        <a [ngClass]="{ 'active': selected == object }"(click)="clicked(object)">{{object.names}}</a>
    </li>
</ul>

但它不起作用。这是我的组成部分:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { objectsService } from './objects.service';
import { object } from './object';


@Component({
  selector: 'objects',
  styles: [require('./object.css')],
  template: require('./objects.html'),
})
export class objects implements OnInit {
  objects: object[];
  codvisita: string;
  selected: any;

  constructor(private route: ActivatedRoute, private objectsService: objectsService) {
  }

  ngOnInit() {
    this.route.params.forEach((params: Params) => {
      this.codvisita = params['id'];
    });
    this.objectsService.getobjects(this.codvisita)
      .subscribe(
        objects => {
          this.objects = objects;
          this.selected = this.objects[0];
          console.log(this.selected);
        }
      );
  }

  clicked(e) {
    this.selected = e;
    console.log(this.selected);
  }
}

1 个答案:

答案 0 :(得分:13)

在您的组件中创建一个变量,我们将其称为temp,然后将temp的值设置为点击事件中的所选对象:

temp: any;

clicked(object) {
    this.temp = object;
}

然后在您的模板中,您可以使用NgClass指令来实现您想要的目标:

<ul id="navbar-example" class="nav nav-pills nav-stacked" *ngFor="let object of objects; let i = index;">
    <li class="nav-item">
        <a id="{{object.code}}" class="nav-link" [ngClass]="{ 'active': temp.code == object.code }" (click)="clicked(object)">{{object.name}}</a>
    </li>
</ul>