[Angular] 마우스 및 키보드 이벤트

[Angular] 마우스 및 키보드 이벤트 updated_at: 2024-02-21 16:27

Input Event

Keyboard Event

html에 적용시

<Element
  (keydown)="onKeyDown()"
  (keyup)="onKeyUp()"
  (keypress)="onKeyPress()"
>

class에 적용시 HostListener 를 이용하여 키보드 이벤트를 가져올 수 있다.

import {HostListener} from '@angular/core'
..........
export class MyComponent {
  @HostListener('document:keyup', ['$event'])
  public onKeyUp(e: any) {
    this.inputAlphabet(e.key.toUpperCase());
  }

  @HostListener('document:mousemove', ['$event']) 
  onMouseMove(e) {
    console.log(e);
  }
..........
}

enter 키 입력확인

input box에서 enter키 를 누를 경우 액션 취하기

  • html
<input type="text" (keydown)="onKeydown($event)">
  • ts
public onKeydown(ev: any) {
  if (ev.key === "Enter") {
    ..........
  }
}

Mouse Event

(mouseover)='onMouseOver($event)'
(mouseenter)="onMouseEnter($event)"
(mousedown)="onMouseDown($event)"
(mouseup)="onMouseUp($event)"
(mouseout)
(mouseleave)
(mousewheel)="onMouseWheel($event)"
(click)="onMouseClick($event)"
(dblclick)
(drag)
(dragover)
(drop)="myMethod()"
(document:mouseout)
  • mouseover: Registers when the cursor is over the element on which this attribute is applied
  • mouseenter:
  • mousedown: Will register the event when the mouse is clicked down, not needing to wait for the click to release
  • mouseup: This event registers when the mouse click is released, so the click down doesn’t need to be done on the element itself
  • mouseout:
  • mouseleave: 위의 마우스아웃과 비슷하다. 하지만 mouse out은 child element 로 옮겨도 이벤트가 발생하지만 mouseleave 는 child로 갈때는 괜찮고 완전히 element를 벗어날때 발생한다.
  • mousewheel:
  • click: Checks for a single click; including the mouse clicking down, and then back up again
  • dblclick: The double click event will register the event when it detects two mouse clicks in a short timeframe
  • drag: Will register when the item is dragged
  • dragover: Registers the event every time an item is dragged over this element
  • drop:
  • document:

mousemove 의 사용예제

class 내에서 사용

import {Component, NgModule, HostListener} from '@angular/core'
..........
export class MyComponent {
  @HostListener('document:mousemove', ['$event'])
  onMouseMove(e) {
    console.log(e);
  }
  ..........
}

html에 적용시
Similar to the above, you can also use (document:event)="handler" on any DOM element, but the above solution is prefered because the code is cleaner. By using this, it's not immediately obvious from the class that you have a global event listener, and you might add additional ones unnecessarily.

@Component({
  selector: 'my-app',
  template: `
    <div (document:mousemove)="onMouseMove($event)" id="box"></div>
  `,
})
export class MyComponent {
  onMouseMove(e) {
    console.log(e);
  }
}

TouchEvent

핸드폰에 주로 사용하는 이벤트

(touchstart)="onTouchStart($event)"
(touchend)="onTouchEnd()"
(touchcancel)="onTouchCancel($event)"
(touchmove)="onTouchMove($event)

전체 문서 영역 선택시 document를 둔다

(document:touchstart)="onTouchStart($event)"
(document:touchend)="onTouchEnd()"
(document:touchcancel)="onTouchCancel($event)"
(document:touchmove)="onTouchMove($event)

MouseEvent vs. TouchEvent

마우스이벤트는 마우스로 제어할때 사용되고 터치이벤트는 터치가 가능한 모바일기기 상에서 가능하므로 서로 호환되지가 않는다.

(mousemove)=(touchmove)
(mousedown)=(touchstart)
(mouseup)=(touchend)

또한 각각 이벤트를 받는 방식이 약간 다르다.

public mousedown = (e: MouseEvent) => { // 마우스 이벤트인 경우 e.Attrbute를 바로 사용
  console.log(e.clientX);
}
public mousemove = (e: MouseEvent) => {
  console.log(e.clientX);
}

public touchstart = (e: TouchEvent) => { // 터치 이벤트인 경우 e.touches[0].Attrbute를  사용
  console.log(e.touches[0].clientX);
}
public touchmove = (e: TouchEvent) => {
  console.log(e.touches[0].clientX);
 }

두 이벤트를 구분하는 방법

if(typeof(window.ontouchstart) == 'undefined') {
  // 마우스 이벤트 적용
} else {
  // 터치 이벤트 적용
}

샘플

두개의 이벤트를 모두 발생시킨 후 선택적으로 사용하는 방법을 취했습니다.(좀 번거러움)
event.type 을 이용하여 구분하는 방법도 있으나 여기서는 window.ontouchstart를 이용하여 전체적으로 구분하여 처리하였습니다.

html

<canvas #nonoCanvas
  (mousemove)="mouseEvent('mousemove', $event)"
  (mousedown)="mouseEvent('mousedown', $event)"
  (mouseup)="mouseEvent('touchend', $event)"
  (touchmove)="mouseEvent('touchmove', $event)"
  (touchstart)="mouseEvent('touchstart', $event)"
  (touchend)="mouseEvent('touchend', $event)"
  (window:resize)="onResize()"
  ></canvas>

class

public mouseEvent(type: string, e: any) {
  if(typeof(window.ontouchstart) == 'undefined') {
    switch (type) {
      case 'touchend': this.mouseup(); break;
      case 'mousedown': this.mousedown(e); break;
      case 'mousemove': this.mousemove(e); break;
    }
  } else {
    switch (type) {
      case 'touchend': this.touchend(); break;
      case 'touchstart': this.touchstart(e); break;
      case 'touchmove': this.touchmove(e); break;
    }
  }
  
}
const handleInputStart = (e: MouseEvent | TouchEvent) => {
  let evt: MouseEvent | Touch;
  // Check if input is from Mobile or Desktop
  if (e.type == "touchstart") {
    evt = (e as TouchEvent).touches[0];
  } else {
    evt = e as MouseEvent;
  }
}

기타이벤트

(focus)="onFocus()" // An element has received focus
(blur)="onBlur()" // An element has lost focus
(submit)="onSubmit()" // A submit button has been pressed
(scroll)="onScroll()"
(cut)="onCut()"
(copy)="onCopy()"
(paste)="onPaste()"

Hammer JS

별도 설명 보기

평점을 남겨주세요
평점 : 5.0
총 투표수 : 2

질문 및 답글