Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created July 1, 2020 23:39
Show Gist options
  • Save allenhwkim/a9ae140d266909873b074de35e690263 to your computer and use it in GitHub Desktop.
Save allenhwkim/a9ae140d266909873b074de35e690263 to your computer and use it in GitHub Desktop.
*inView
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