Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle class only current element angular2

here is my code examples. In my case toggle class works for every li element

   <ul class="nav nav-pills pull-right">
        <li *ngFor="let x of nav" class="presentation" (click)="active = !active" [ngClass]="toggleClass()">
            <a href="#">{{x.menu}} </a>
        </li>
    </ul>

js

 export class AppComponent {
  active = false;
  nav = NAVIGATION;

  //Toggle Class

  toggleClass(){
    if(this.active){
      return 'active';
    } else {
      return '';
    }
  }
like image 982
Val Do Avatar asked Jan 17 '17 08:01

Val Do


1 Answers

With following code, you don't need to write typescript code,

<ul class="nav nav-pills pull-right">
        <li *ngFor="let x of nav;let i=index" 
             class="presentation" 
             (click)="isClicked=i"             
             [class.active]="isClicked==i">    
             <a href="#">{{x.menu}}</a>
        </li>
</ul>
like image 100
Nikhil Shah Avatar answered Oct 08 '22 08:10

Nikhil Shah