How highlight a div on click in angular

I am having div called booking-list,which i am using to display the booking timings.Here on mouse hover the background-color of the div is changing as shown in below image.

enter image description here

Here my issue is,suppose if i click on the first timings(i,e september1) that div's background as to be changed and that background color should to be constant until i click next timings.something like this below image.I got resources for list component but i am unable to apply it for div

enter image description here

Here is the stackblitz link.

2 answers

  • answered 2018-09-17 06:09 Swoox

    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 }


    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); }

  • answered 2018-09-17 06:16 Joel Richman

    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:


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


    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;


    .selected {
      background-color: aqua;

    Here is an updated StackBlitz.