Vugar Ahmadov
Vugar Ahmadov

Reputation: 329

give active class onclick in ngFor angular 2

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

Answers (5)

Jhonatan Soares
Jhonatan Soares

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

doppelgunner
doppelgunner

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

s-gbz
s-gbz

Reputation: 541

I'd like to add & clarify a possible misconception:

  • You can only add classes via via [ngClass].
  • You can NOT add selectors like the :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

Eduardo Vargas
Eduardo Vargas

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

Patrick McDermott
Patrick McDermott

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

Related Questions