Angular2 - Add class to item on click
You need to make an array in your class to store highlight status of an item:
hightlightStatus: Array<boolean> = [];
Declare local variable in the template associated with ngFor:
<ul>
<li [attr.data-selected]="false"
(click)="hightlightStatus[i]=!hightlightStatus[i]"
[class.highlight]="hightlightStatus[i]"
*ngFor="let item of items, let i = index">
{{item}}
</li>
</ul>
There are many ways to achieve this, and all are very simple.
Examples:
<li *ngFor="let n of list" (click)="select(n)" [ngClass]="{active: isActive(n)}">
<a>{{n}}</a>
</li>
select(item) {
this.selected = item;
};
isActive(item) {
return this.selected === item;
};
Only using html
<li *ngFor="let n of list" [class.active]="clicked === n"
(click)="clicked = n">
<a>{{n}}</a>
</li>
Add class on click and remove if we click on the same
select(item) {
this.selected = (this.selected === item ? null : item);
};
Only using html
<li *ngFor="let n of list" [class.active]="clicked === n"
(click)="clicked = (clicked === n ? null :n)">
<a>{{n}}</a>
</li>
More info
If I am understanding the question properly, I believe you can also use the render from angular2 to get a similar code to your example code. For my own project I did the following:
In my template I have:
<li role="presentation" (click)="userTypeSelect($event)" ><a href="#">Local</a></li>
In my component I then have:
import {Renderer} from '@angular/core';
//other imports
export class SignupComponent implements OnInit {
constructor(private render:Renderer) { }
userTypeSelect(event:any){
event.preventDefault()
this.render.setElementClass(event.target,"active",false);
}
}
It is worth noting though that I am not using this for a list of items, however I believe it should still work.
Reference to the Renderer: Renderer Api Docs