0

I have dynamically created a table using nested ngFor loops. When I mouseover one of the spans the background colour changes for all of the spans. The behaviour I want and expect is that the background will change only on the span that I am on and not for all of them at the same time.

<div *ngFor="let col of table; let j=index">
  <span *ngFor="let row of col; let i=index" (mouseover)="hover=true" (mouseleave)="hover=false" [ngStyle]="{backgroundColor: hover==true ? 'lightblue' : 'transparent'}">{{ row['r' + j + 'c' + i] }}
  </span>
</div>

This is how the table object was created,

table: {}[] = [];
  cols: {}[]= [];
  cell: {}= null;
  c:number;
  r:number;
  key: string = null;
  rowslength:number = 2;
  columnslength:number = 2;

  constructor() {
    this.makeTable();
  }

    makeTable(){
          for(this.r = 0; this.r < this.rowslength; this.r++){
            for(this.c = 0; this.c < this.columnslength; this.c++){
              this.key = "r" + this.r + "c" + this.c;
              this.cell = { [this.key]: this.key };
              this.cols.push(this.cell);
            }
            this.table.push(this.cols);
            this.cols = [];
        }
      }
Shane G
  • 3,129
  • 10
  • 43
  • 85
  • 1
    You're using a boolean `hover` variable in order to specify that the row i and column j is hovered. That can't possibly work. A boolean can't store a row and a column. Store the row and the column of the hovered cell instead. And apply the background color on a cell if its row and its column are equal to the row and column of the hovered cell. – JB Nizet Jul 01 '17 at 08:44
  • Ok I thought it should just apply to the span being hovered over. Thanks for your explanation, I'll get to work on it. – Shane G Jul 01 '17 at 08:55

1 Answers1

0

To highlight the cell being mouseovered.

    <div *ngFor="let col of table; let j=index">
      <span *ngFor="let row of col; let i=index" 
          (mouseover)="columni=i; rowj=j" 
          [ngStyle]="{backgroundColor: 
          rowj==j && columni==i ? 'lightblue':'transparent'}">
      {{ row['r' + j + 'c' + i] }}
      </span>
    </div>
Shane G
  • 3,129
  • 10
  • 43
  • 85