Search code examples
htmlcssangularng-class

Angular 2: Adding ngClass to the element based on the click event


I want Clicked class to be applied only to one clicked element at a time. Upon clicking other element the first clicked element should not have that class any more. It should be somewhat like this.clicked to that particular element.
Click here for the desired output

  .rangeContainer{
    width: 100%;
    height: 46px;
    }
    .range{
      height: 42px;
      background-color: #F6F6F6;
      color: #035688;
      font-size: 12px;
      font-weight: 800;
      line-height: 46px;
      padding: 15px 20px;
      cursor: pointer;
    }
    .clicked{
      background-color: white;
      color: #7A232E;
      border-top: 6px solid #7A232E;
    }
  
I want the 
   
<div class="rangeContainer">
    <span (click)="click = !click" [ngClass]="{'clicked' : click}" class="range">K4 - K5</span>
    <span (click)="click = !click" [ngClass]="{'clicked' : click}"class="range">1ST - 2ND</span>
    <span (click)="click = !click" [ngClass]="{'clicked' : click}"class="range">3RD - 4TH</span>
    <span (click)="click = !click" [ngClass]="{'clicked' : click}"class="range">5TH - 8TH</span>
</div>


Solution

  • <span
      *ngFor="let range of ['K4 - K5', '1ST - 2ND', '3RD - 4TH', '5TH - 8TH']; let i = index"
      (click)="activeIndex = i"
      [ngClass]="{ clicked : activeIndex === i }" class="range" >
      {{ range }}
    </span>
    

    Plunker Example