Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz.
The row selection functionality is implemented using mouse event handlers (mousedown
, mousemove
, mouseup
).
Below is the template code from table.comp.html
:
<table class="table table-hover">
<tbody>
<tr *ngFor="let td of data; let i = index"
(mousedown)="onSelectionStart(i)"
(mousemove)="onSelection(i)"
(mouseup)="onSelectionEnd()"
[class.selected]="td">
<td>row {{ i }}</td>
<td>selected: {{ td }}</td>
</tr>
</tbody>
</table>
Here is the code for the Component
(table.comp.ts
) containing the event handlers:
export class TableComponent {
private data: Array<any> = [];
constructor() {
[1, 2, 3, 4].forEach(x => this.data.push(false))
}
mouseDown: boolean = false;
select: boolean = false;
onSelectionStart(index) {
this.mouseDown = true;
this.select = !this.data[index];
}
onSelection(index) {
if (!this.mouseDown)
return;
this.data[index] = this.select;
console.log("You see me many times!");
}
onSelectionEnd() {
this.mouseDown = false;
}
}
Objectives:
Prevent multiple re-selections of the same item. The message
"You see me many times!"
should only display once per row.Utilize RxJs to achieve the first objective.
Note: This code is based on Angular 2 RC3 and RxJs 5