본문 바로가기

개발 공부/Angular

@HostListener

@HostListener

@HostListener는 Angular의 데코레이터 중 하나로, DOM 이벤트를 감지하고 해당 메서드로 연결할 수 있게 해주는 기능입니다.

컴포넌트 또는 디렉티브 클래스 내부에 정의되며, 이벤트의 대상은 호스트 엘리먼트입니다.

 

 

@HostListener('click', ['$event'])
onClick(event: Event) {
  console.log('클릭됨!', event);
}
  • 위 코드는 해당 요소가 클릭되었을 때 onClick() 메서드를 실행시킵니다.

 

왜 @HostListener를 사용할까?

일반적으로 이벤트 바인딩을 템플릿에서 (click)="handler()" 이런 식으로 작성합니다.

그런데 @HostListener는 다음과 같은 상황에서 유리합니다

  • 디렉티브나 공통 컴포넌트에서 재사용할 때
  • DOM에 직접 접근하지 않고 이벤트 처리할 때 (Angular 방식으로 유지)
  • 마우스 오버, 스크롤, 키보드 입력 등 다양한 이벤트를 명확하고 구조적으로 관리할 때

 

 

주요 문법

@HostListener('이벤트이름', ['전달받을 값'])
methodName(파라미터) {
  // 이벤트 핸들러 로직
}

 

 

파라미터 예시 설명
$event 기본 이벤트 객체
$event.target 이벤트가 발생한 DOM 요소
$event.clientX 마우스 X 좌표

 

 


 

자주 쓰는 이벤트 예시

@HostListener('mouseenter') onMouseEnter() {
  this.isHovering = true;
}

@HostListener('mouseleave') onMouseLeave() {
  this.isHovering = false;
}

@HostListener('window:scroll', []) onWindowScroll() {
  console.log('윈도우 스크롤 감지!');
}

@HostListener('document:keydown.enter', ['$event']) onEnterKey(event: KeyboardEvent) {
  console.log('엔터키 눌림:', event);
}

 

 

 


예시

window:scroll 로 무한 스크롤 감지하기

스크롤이 하단에 도달했을 때 API 호출 → 무한 스크롤 구현

@HostListener('window:scroll', [])
onScroll(): void {
  const scrollPosition = window.innerHeight + window.scrollY;
  const threshold = document.body.offsetHeight - 100;

  if (scrollPosition >= threshold && !this.isLoading) {
    this.loadMoreData();
  }
}

 

  • window.scrollY: 현재 스크롤 위치
  • window.innerHeight: 보이는 영역 높이
  • document.body.offsetHeight: 전체 문서 길이
  • 하단에서 100px 이내에 들어오면 추가 데이터 요청

 

 

window:resize 로 반응형 상태 감지

@HostListener('window:resize', [])
onResize(): void {
  this.isMobile = window.innerWidth < 768;
}

 

  • 디바이스의 해상도에 따라 모바일 UI 또는 PC UI 로직 분기
  • this.isMobile을 활용해 ngIf, ngClass 등에서 조건 처리

 

 

document:click 으로 외부 클릭 감지 (드롭다운 닫기)

@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent): void {
  const clickedInside = this.elementRef.nativeElement.contains(event.target);
  if (!clickedInside) {
    this.isDropdownOpen = false;
  }
}

 

 

 

  • 디렉티브나 컴포넌트 외부 클릭을 감지하여 팝업/모달 닫기
  • contains() 를 사용해 클릭이 내부인지 외부인지 판별

 

 

keydown.esc 로 ESC 키 처리

@HostListener('document:keydown.escape', ['$event'])
onEscKey(event: KeyboardEvent): void {
  if (this.isModalOpen) {
    this.closeModal();
  }
}

 

  • ESC 키 눌렀을 때 모달 닫기
  • 사용자의 키보드 인터랙션에 대한 접근성(accessibility) 향상

'개발 공부 > Angular' 카테고리의 다른 글

컴포넌트 인클루전 방식 vs 라우트 분리 방식  (0) 2025.05.27
Angular computed()  (0) 2025.05.26
Angular Directive  (0) 2025.05.17
Angular Route Guard (canActivateChild, canDeactivate, canLoad )  (0) 2025.03.17
Angular Resolve  (0) 2025.03.15