FacundoGFlores FacundoGFlores - 1 month ago 27
TypeScript Question

Angular2 - Adding CSS class to selected element

I have the following code in my

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


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

EDIT:

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>
</li>
</ul>


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


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

Answer

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>
    </li>
</ul>
Comments