简体   繁体   中英

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..

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>

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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM