forgottofly
forgottofly

Reputation: 2719

Highlighting selected elements in angular *ngFor

I'm trying to highlight and keep the selected element active by applying a border class in my angular 2 application.But on selecting the child element under any year selects all its corresponding child components of other years. I wanted to highlight only the selected element.

Please find the plunker link here

Code used to highlight selected element:

this.setClickedRow = function(index){
         console.log(index);
            this.selectedRow = index;
        }

Note:On hover I'm applying class item-hover that is working fine for individual child elements.

Please let me know if anyone has faced similar issue like this before..

Upvotes: 1

Views: 3761

Answers (2)

Eduardo Vargas
Eduardo Vargas

Reputation: 9402

Hi I fixed it in a new plunker here ->

https://plnkr.co/edit/Cys2iGOQxWGta3KjRL9f?p=preview

The key is to map your array to a selected attribute and use the view based on that.

this.quarterDataList.map(quarter =>{
      quarter.selected=false;
      return quarter;
})  

And on the html

<div class="item-hover" *ngFor="let count of item.quarterData;let i = index" (click)="count.selected=!count.selected" [class.active]="count.selected">

Upvotes: 1

Gaurav Srivastava
Gaurav Srivastava

Reputation: 3232

change your template to this:

<div class="border-box">
    <div  *ngFor="let item of quarterDataList">
      <h2>{{item.year}}</h2>
      <div class="item-hover" *ngFor="let count of item.quarterData;let i = index" (click)="setClickedRow((i+'_'+item.year))" [class.active]="((i+'_'+item.year)) == selectedRow">
        <br>
       {{count.view}}-{{count.count}}
    </div>
    </div>

  </div>

Upvotes: 2

Related Questions