title: Angular2 - Adding CSS class to selected element
body: <p>I have the following code in my <code>.html</code>:</p>
  
  <pre><code>&lt;ul id="navbar-example" class="nav nav-pills nav-stacked" *ngFor="let object of objects; let i = index;"&gt;
      &lt;li class="nav-item" *ngIf = "i==0"&gt;
          &lt;a id="{{object.code}}" class="nav-link active" (click)="clicked(object)"&gt;{{object.name}}&lt;/a&gt;
      &lt;/li&gt;
      &lt;li class="nav-item" *ngIf = "i!=0"&gt;
          &lt;a id="{{object.code}}" class="nav-link" (click)="clicked(object)"&gt;{{object.name}}&lt;/a&gt;
      &lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>So the first element is active when the <code>ul</code> is loaded. Now I want to add the <code>active</code> class to the selected <code>&lt;a&gt;&lt;/a&gt;</code> and toggle that  which has <code>active</code>. How can I achieve it?</p>
  
  <p>EDIT:</p>
  
  <p>I simplified to this:</p>
  
  <pre><code>&lt;ul id="navbar-example" class="nav nav-pills nav-stacked" *ngFor="let object of objects;"&gt;
      &lt;li class="nav-item" &gt;
          &lt;a [ngClass]="{ 'active': selected == object }"(click)="clicked(object)"&gt;{{object.names}}&lt;/a&gt;
      &lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>but it does not work. This is my component:</p>
  
  <pre><code>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) =&gt; {
        this.codvisita = params['id'];
      });
      this.objectsService.getobjects(this.codvisita)
        .subscribe(
          objects =&gt; {
            this.objects = objects;
            this.selected = this.objects[0];
            console.log(this.selected);
          }
        );
    }
  
    clicked(e) {
      this.selected = e;
      console.log(this.selected);
    }
  }
  </code></pre>