Asif Karim Bherani
Asif Karim Bherani

Reputation: 1093

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>

Upvotes: 3

Views: 4218

Answers (2)

yurzui
yurzui

Reputation: 214315

<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

Upvotes: 6

Chrillewoodz
Chrillewoodz

Reputation: 28368

In component:

// Insert your real labels here
this.items = [{label: 'item 1'}, {label: 'item 2'}];

Then use a *ngFor:

<div class="rangeContainer">
    <span *ngFor="let item of items" (click)="toggleClick(item)" [ngClass]="{'clicked' :item.isClicked}" class="range">{{item.label}}</span>
</div>

Then toggle like this:

toggleClick(clickedItem: any): void {

  for (let item of items) {
    item.isClicked = false;
  }

  clickedItem.isClicked = true;
}

This will ensure only 1 item is clicked at one time. I'm using a loop so I can store that clicked state on the object instead. It makes life easier.

Upvotes: 1

Related Questions