본문 바로가기
Angular.js

[angular.js] 화면에서 div가 안보일때 동작하는 directive 기능 제작

by 갈잃자 2024. 6. 26.

개요: 화면상, 어떠한 버튼이 사라지면, 아래에 fixed 되어 나오는 버튼을 제작하다가 종종 쓰이겠다 싶어서 directive로 제작


IntersectionObserver란?

  • js에서 제공하는 인터페이스
  • 대상 요소와 상위 요소, 또는 대상 요소와 최상위 문서의 뷰포트가 서로 교차하는 영역이 달라지는 경우 이를 비동기적으로 감지할 수 있는 수단

 

쉽게 얘기하면, 내 화면에 IntersectionObserver가 감지하고 있는 html 태그가 보이냐 마냐를 판단하는 인터페이스임

 

이걸 directive로 제작하여, 태그에 편리하게 달아줄 수 있을거 같다!

(directive로 제작하면, 매 함수 불러다 쓸 필요없이 html에 직접적으로 표현할 수 있음!)

 

import { Directive, ElementRef, EventEmitter, Output } from '@angular/core';


@Directive({
  selector: '[lfVisibilityObserver]' //요 selector 를 앞으로 이 기능이 필요한 html에 붙여주면됨
})
export class VisibilityObserverDirective {
  @Output() visibilityChange: EventEmitter<boolean> = new EventEmitter<boolean>();
  private observer: IntersectionObserver;

  constructor(
    private elementRef: ElementRef
  ) {
  
    // IntersectionObserver 생성
    this.observer = new IntersectionObserver(entries => {
      entries.forEach(entry => this.visibilityChange.emit(entry.isIntersecting));
    });

    this.observer.observe(this.elementRef.nativeElement);
  }

  ngOnDestroy() {
    this.observer.disconnect();
  }
}

 

    <div class="my-agent-top-box"
		 lfVisibilityObserver <- (요런식으로)
         (visibilityChange)="onVisibilityChange($event)"
    >
    
    </div>

혹시 ui 개발 하고있으시면 써보삼 개쩜 -> (IntersectionObserver)

 

IntersectionObserver 기능은 아래 참고

https://developer.mozilla.org/ko/docs/Web/API/IntersectionObserver

댓글