Last active
June 9, 2017 14:28
-
-
Save fredrik-lundin/900596dc1cd35d08c2ae6985e0c21f05 to your computer and use it in GitHub Desktop.
IsInViewDirective (https://plnkr.co/edit/dAkDNTPBNGahg4Kct8IM?p=preview)
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 {Component, NgModule, ContentChild, | |
Directive, Input, HostListener | |
ContentChildren, QueryList, | |
forwardRef, ElementRef | |
} from '@angular/core' | |
import {BrowserModule} from '@angular/platform-browser' | |
@Component({ | |
selector: 'my-app', | |
template: ` | |
<div scrollIntoViewWrapper style="background: blue; height: 2000px;"> | |
<div scrollIntoViewElement style="height: 100px;"></div> | |
<div scrollIntoViewElement style="height: 100px; margin-top: 400px"></div> | |
<div scrollIntoViewElement style="height: 100px; margin-top: 400px"></div> | |
<div scrollIntoViewElement style="height: 100px; margin-top: 400px"></div> | |
</div> | |
`, | |
styles: [` | |
div { background: red; } | |
.element-seen { background: green; } | |
`] | |
}) | |
export class App {} | |
@Directive({selector: '[scrollIntoViewWrapper]'}) | |
export class ScrollIntoViewWrapper { | |
@ContentChildren(forwardRef(() => ScrollIntoViewElement)) contentChildren; | |
ngAfterViewInit() { | |
this.onWindowScroll() | |
window.onscroll = () => this.onWindowScroll(); | |
} | |
ngOnDestroy() { | |
console("destroyed"); | |
window.onscroll = null; | |
} | |
onWindowScroll() { | |
if(!this.contentChildren) return; | |
this.contentChildren.forEach(el => { | |
const htmlEl = el.el.nativeElement; | |
if(this.isScrolledIntoView(el.el.nativeElement)) { | |
htmlEl.classList.add("element-seen"); | |
} | |
}); | |
} | |
isScrolledIntoView(el) { | |
const elemTop = el.getBoundingClientRect().top; | |
const elemBottom = el.getBoundingClientRect().bottom; | |
return (elemTop >= 0) && (elemBottom <= window.innerHeight); | |
} | |
} | |
@Directive({selector: '[scrollIntoViewElement]'}) | |
export class ScrollIntoViewElement { constructor(public el: ElementRef) {}} | |
@NgModule({ | |
imports: [ BrowserModule ], | |
declarations: [ App, ScrollIntoViewWrapper, ScrollIntoViewElement ], | |
bootstrap: [ App ] | |
}) | |
export class AppModule {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment