In an Angular 2 app, i want the click event to trigger something different when the shift key is being held down. how to achieve this?
html is below:
<div class="item" *ngFor="#obj of available" (click)="toggleSelected(obj)"></div>
and i want to do something like this:
toggleSelected(obj) {
if(shift is pressed) {
do this
} else {
do that
}
}
so how can i detect if shift key is pressed? thanks!
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
}
}
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>
Here are some additional tweaks, which may be useful:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With