본문 바로가기

개발/Angular

[Angular] @ViewChild를 활용한 스크롤 이벤트 처리

div의 스크롤이 바닥까지 갔는지 체크하고 동적으로 class 변경하는 처리


@ViewChild 활용

스크롤 영역에 템플릿 참조 변수 추가

// html
<div #scrollAreaWrapper [class.is-bottom-gradient]="!isBottom">
	// 내용 생략 블라블라
</div>

 

@ViewChild를 사용하여 요소에 접근

// ts
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-test-scroll',
  templateUrl: './test-scroll.component.html',
})
export class TestScrollComponent implements AfterViewInit {
  @ViewChild('scrollAreaWrapper', { static: false }) scrollWrapper: ElementRef;
  isBottom = false;


  ngAfterViewInit() {
    this.scrollWrapper.nativeElement.addEventListener('scroll', this.scrollEvent.bind(this));
  }

  scrollEvent(event) {
    const scrollWrapper = this.scrollWrapper.nativeElement;
    if (
      scrollWrapper.scrollTop + scrollWrapper.clientHeight >=
      scrollWrapper.scrollHeight
    ) {
      this.isBottom = true;
    } else {
      this.isBottom = false;
    }
  }

 

 

실패했던 방법

스크롤 영역에 id를 주고 addEventListener로 스크롤을 감지해 값을 변경함

내부적으로 값은 변하지만 DOM에서 변한 값이 렌더링 되지는 않았음.

window.addEventListener('scroll', this.scrollEvent, true);