pwborodich
pwborodich

Reputation: 382

Highlight [class.active] of nested ngFor element in Angular2

I am displaying my nested for loop correctly but I am having trouble when highlighting the individual selected li element in the nested array, so the undesired result is everything in that row highlights based on whatever number i is.

 <div class="nopadding week" style="width: 12%;" *ngFor="let day of Schedule; let j = index">
      <ul class="nopadding">
          <div *ngFor="let hour of day.hours; let i = index" class="hours">
            <li class="hour" [ngClass]="{watched: hour.assignments.length> 0, unassigned: hour.assignments.length <= 0}" (click)="selectedtimeslot(hour.assignments, i)" [class.active]="i == selectedRow">
              {{hour.assignments.length}}
            </li>
          </div>
        </div>
      </ul>
    </div>

In my component I have the function that set that value of the selected row.

selectedtimeslot(item: any, index:any) {
    this.selectedRow = index;
    this.highlightGuardian.changeNav(item);
}

scss

li.active {
   background-color:#123456 !important;
   color: white;
}

I think I know my problem is that I am nit giving the [class.active] any information about the parents index in order to correctly highlight the selected element

Upvotes: 0

Views: 895

Answers (1)

Joo Beck
Joo Beck

Reputation: 1913

You are correct that your issue is you aren't giving it any parent information, so it is highlighting the selected index of every parent.

Instead of making your selectedRow be equal to a number, make it an hour, and send it the hour, like so.

      <div *ngFor="let hour of day.hours; let i = index" class="hours">
        <li class="hour" [ngClass]="{watched: hour.assignments.length> 0, unassigned: hour.assignments.length <= 0}" (click)="selectedtimeslot(hour.assignments, hour)" [class.active]="hour == selectedRow">
          {{hour.assignments.length}}
        </li>
      </div>

This will ensure that it only matches that single div, as it will do an object compare, instead of an index compare.

Upvotes: 1

Related Questions