如何在用angular2单击时更改表格单元的背景颜色? [英] How to change the background color of a tablecell on click with angular2?
问题描述
我有一张桌子,我想在单元格上单击以突出显示和取消突出显示该单元格(更改单元格的背景)。我的HTML看起来像这样:
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>
和我的班级:
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);
}
我的问题是,现在并未在该项目上调用click事件,而是而不是点击。无论我在哪里单击单元格,单击的次数都会从false变为true,但是单元格项不会保持其状态。
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?
推荐答案
我要做的是要么存储ID数组(如果可以选择多行),要么包含您的ID的变量(用于单选)。
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).
让我们简单一点:
selected: '';
onClick(weekday, time){
if(this.selected === weekday) {
this.selected = '';
} else {
this.selected = weekday;
}
}
在您的HTML中:
<th *ngFor="let weekday of weekdaysForClick"
(click)="onClick(weekday, time)" [ngClass] = "'active'" [class.selected]="selected === weekday"></th>
这篇关于如何在用angular2单击时更改表格单元的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!