Created
July 1, 2020 23:39
-
-
Save allenhwkim/a9ae140d266909873b074de35e690263 to your computer and use it in GitHub Desktop.
*inView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Directive, Component, Input, ViewContainerRef, TemplateRef, AfterViewInit} from '@angular/core'; | |
@Directive({selector: '[inView]'}) | |
export class InView implements AfterViewInit { | |
alreadyRendered: boolean; // cheking if visible already | |
constructor( | |
private vcRef: ViewContainerRef, | |
private tplRef: TemplateRef<any> | |
) {} | |
ngAfterViewInit() { | |
const commentEl = this.vcRef.element.nativeElement; // template | |
const elToObserve = commentEl.parentElement; | |
this.setMinWidthHeight(elToObserve); | |
const observer = new IntersectionObserver(entries => { | |
entries.forEach(entry => { | |
this.renderContents(entry.isIntersecting) | |
}); | |
}, {threshold: [0, .1, .9, 1]}); | |
observer.observe(elToObserve); | |
} | |
renderContents(isInView) { | |
if (isInView && !this.alreadyRendered) { | |
this.vcRef.clear(); | |
this.vcRef.createEmbeddedView(this.tplRef); | |
this.alreadyRendered = true; | |
} | |
} | |
setMinWidthHeight(el) { // prevent issue being visible all together | |
const style = window.getComputedStyle(el); | |
const [width, height] = [parseInt(style.width), parseInt(style.height)]; | |
!width && (el.style.minWidth = '40px'); | |
!height && (el.style.minHeight = '40px'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment