Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: check if shift key is down when an element is clicked

Tags:

angular

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!

like image 280
totoro Avatar asked May 06 '16 18:05

totoro


2 Answers

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
  }
}
like image 99
Michael Liu Avatar answered Oct 23 '22 04:10

Michael Liu


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);
  }
}
like image 27
bvdb Avatar answered Oct 23 '22 04:10

bvdb