FacundoGFlores FacundoGFlores - 1 year ago 269
TypeScript Question

Angular2 - Adding CSS class to selected element

I have the following code in my


<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 class="nav-item" *ngIf = "i!=0">
<a id="{{object.code}}" class="nav-link" (click)="clicked(object)">{{object.name}}</a>

So the first element is active when the
is loaded. Now I want to add the
class to the selected
and toggle that which has
. How can I achieve it?


I simplified to this:

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

but it does not work. This is my component:

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

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'];
objects => {
this.objects = objects;
this.selected = this.objects[0];

clicked(e) {
this.selected = e;

Answer Source

Create a variable in your component, let's call it temp and then set value of temp to selected object in your click event:

temp: any;

clicked(object) {
    this.temp = object;

And then in your template you can use NgClass directive to achieve what you want:

<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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download