How to change the background color of a tablecell on click with angular2?

落爺英雄遲暮 提交于 2019-12-24 19:33:40

问题


I have a table and I would like to highlight and unhighlight a cell(change the background of the cell)of the table on click on the cell. My HTML looks like that:

<table class="table table-bordered">
        <thead>
          <tr>
            <th *ngFor="let weekday of weekdays">
                <div>{{weekday}}</div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr scope="row" *ngFor="let time of times"><td>{{time}}</td>
            <th scope="row" class = 'success' *ngFor="let weekday of weekdaysForClick"
             (click) = "onClick(weekday, time)" [ngClass] = "'active'" [class.selected]="weekday.clicked"></th> 
         </tr>
         </tbody>
</table>

and my class:

    weekdays : string[] = ['#','Monday', 'Thusday', 'Wednesday', 'Thursday', 'Friday' ]
    times: string[] = ['8:30 - 9:15', '9:15 - 10:00', '10:15 - 11:00', '11:00 - 11:45', '12:30 - 13:15', '13:15 - 14:00', '14:15 - 15:00']
    weekdaysForClick : string[] = ['Monday', 'Thusday', 'Wednesday', 'Thursday', 'Friday' ]
    wasClicked = false;

    onClick(weekday, time){

        this.wasClicked= !this.wasClicked;
        console.log(this.wasClicked)
        console.log(weekday, time);
    }

My problem is that right now the click event is not called on the item but rather called on the click. Whereever I click on my cells the was click chanching from false to true, but the cell item not holds it state.

What would be a good solution to register click event per cell item?


回答1:


What I would do is either store an array of IDs (if you can select multiple lines), or a variable containing your ID (for a single selection).

Let's go with simple :

selected: '';

onClick(weekday, time){
  if(this.selected === weekday) {
    this.selected = '';
  } else {
    this.selected = weekday;
  }
}

In your HTML :

<th *ngFor="let weekday of weekdaysForClick"
         (click)="onClick(weekday, time)" [ngClass] = "'active'" [class.selected]="selected === weekday"></th>


来源:https://stackoverflow.com/questions/49234862/how-to-change-the-background-color-of-a-tablecell-on-click-with-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!