Reputation: 329
Hi I have unordered list and all of them have active class. I want to toggle active class when clicked to any list item. My code is like this
<ul class="sub_modules">
<li *ngFor="let subModule of subModules" class="active">
<a>{{ subModule.name }}</a>
</li>
</ul>
can anyone help me to do this?
Upvotes: 19
Views: 65133
Reputation: 1
the loop
<div *ngFor="let item of divs; let i = index">
<app-cool [index]="i"></app-cool>
</div>
the <app-cool></app-cool> html
<div (click)="setActive()" [class.active]="isActive()">
</div>
the <app-cool></app-cool> ts
static activeIndex = -1;
@Input() index: number = -1;
public setActive(): void{
ThisClass.activeIndex = this.index;
}
public isActive(): boolean{
return ThisClass.activeIndex === this.index;
}
Upvotes: 0
Reputation: 649
just make an index property. use let i = index
to set the index using (click) event. Then check if selectedIndex === i
if yes the set class "active" to true
<ul class="sub_modules">
<li *ngFor="let subModule of subModules; let i = index"
[class.active]="selectedIndex === i"
(click)="setIndex(i)">
<a>{{ subModule.name }}</a>
</li>
</ul>
Then on typescript file: just set selectedIndex.
export class ClassName {
selectedIndex: number = null;
setIndex(index: number) {
selectedIndex = index;
}
}
Upvotes: 45
Reputation: 541
I'd like to add & clarify a possible misconception:
[ngClass]
.:active
selector.<li [ngClass]="{'active': isActive === true}">
Mind the difference:
.li.active {
// This works! :)
}
.li:active {
// This doesn't work! :(
}
It might be obvious for some, but took me ~15 minutes of trial & error to understand.
Upvotes: 1
Reputation: 9402
You can do something like:
<ul class="sub_modules">
<li (click)="activateClass(subModule)"
*ngFor="let subModule of subModules"
[ngClass]="{'active': subModule.active}">
<a>{{ subModule.name }}</a>
</li>
</ul>
On The component
activateClass(subModule){
subModule.active = !subModule.active;
}
On the Ng class the first property is the class you wanna add and the second is the condition;
Upvotes: 27
Reputation: 1220
I believe you can find your answer here: AngularJs - Best-Practices on adding an active class on click (ng-repeat)
You can target and apply CSS to an item/object through Angular's $index
. The post explains and demonstrates the logic better than I can.
Upvotes: 1