Skip to content

Instantly share code, notes, and snippets.

@fredrik-lundin
Last active June 9, 2017 14:28
Show Gist options
  • Save fredrik-lundin/900596dc1cd35d08c2ae6985e0c21f05 to your computer and use it in GitHub Desktop.
Save fredrik-lundin/900596dc1cd35d08c2ae6985e0c21f05 to your computer and use it in GitHub Desktop.
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