Angular 2: check if shift key is down when an element is clicked
Your question may refer to multi-select option for records of a table.
In that case you could store the selected objects in a set.
public selectedRowSet: Set<MyObject> = new Set();
Each time a record is selected, you use the following method to add them to a set.
public setSelectedRow(obj: MyObject, event: MouseEvent) {
if(!event.shiftKey) {
selectedRowSet.clear();
}
selectedRowSet.add(obj);
}
Then you probably want to add conditional formatting.
public isRowSelected(obj: MyObject): boolean
{
return selectedRowSet.has(obj);
}
In your view use:
<tr *ngFor="let obj of myObjectCollection"
[class.someCssClass]="isRowSelected(obj)"
(click)="setSelectedRow(obj, $event);">
...
</tr>
REVIEW
Here are some additional tweaks, which may be useful:
- you can choose to use Shift or Ctrl or ⌘ (for apple)
- records can also be deselected if this key is pressed.
I hope this is useful for somebody.
public setSelectedRow(bo: Bo, event: MouseEvent) {
// support shift, control and the command key.
const add = event.shiftKey || event.ctrlKey || event.metaKey;
if (!add) {
this.selectedRowSet.clear();
this.selectedRowSet.add(bo);
return;
}
// toggle selected record
if (this.selectedRowSet.has(bo)) {
this.selectedRowSet.delete(bo);
}
else {
this.selectedRowSet.add(bo);
}
}
In the (click)
binding, pass the $event
object to the toggleSelected
method:
<div class="item" *ngFor="#obj of available" (click)="toggleSelected(obj, $event)"></div>
In the toggleSelected
method, check whether the event's shiftKey
property is true
:
toggleSelected(obj, event) {
if (event.shiftKey) {
// do this
} else {
// do that
}
}