How highlight a div on click in angular

One way is to store the selected item when you click on the div and then use the ngClass directive to apply a class to the selected item:

Markup:

<div class="booking-list" 
   *ngFor="let batch of batches" 
   (click)="onClick(batch)" 
   [ngClass]="{ 'selected': batch == selectedItem }">

Component:

selectedItem = null;

  public batches: IBatch[] = [
    {name: 'Regular', month: 'September 1', time: '10:30 AM - 5:00 PM' , slots: '20/25', color: 'blue'  },
    {name: 'Weekend', month: 'September 10', time: '10:30 AM - 5:00 PM' , slots: '15/25', color: 'red'  },
    {name: 'Weekend', month: 'August 10', time: '12:30 AM - 8:00 PM' , slots: '21/25', color: 'red'  },
  ];

  onClick(item) {
    this.selectedItem = item;
  }

css:

.selected {
  background-color: aqua;
}

Here is an updated StackBlitz.


I found that [ngClass] was giving me problem with multiple select so here is what I came up with. stackblitz

  • multi selector / multi-select

Ok so this is pretty easy to do with ngClass. You make a highlight class in your css. What this will do is it will check if the condition is true and apply the css.

Then you do in the ngFor:

*ngFor="let item of item; let i = index;" (click)="setRow(i)" [ngClass]="{'highlight': selectedIndex === i}"

And then in your component:

public setRow(_index: number) { this.selectedIndex = _index;

In your css you can do something like:

.highlight{ background-color: green }

EDIT

For multi-selection you can do:

[ngClass]="{'highlight': selectedIndexs.indexOf(i)}

public setRow(_index: number) { if (this.selectedIndexs.indexOf(_index) === -1) { this.selectedIndexs.push(_index); } else { let index = this.selectedIndexs.indexOf(_index); this.selectedIndexs.splice(index, 1); }