Last active
October 26, 2020 15:18
-
-
Save tkutcher/3863b53ea5bc2d766fb22a4b55cac6ca to your computer and use it in GitHub Desktop.
Angular Anchor Routing
This file contains 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, Inject, OnInit, PLATFORM_ID } from '@angular/core'; | |
import { Router, Event, Scroll } from '@angular/router'; | |
import { isPlatformBrowser } from '@angular/common'; | |
// https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/ | |
const isInViewport = (elem) => { | |
const bounding = elem.getBoundingClientRect(); | |
return ( | |
bounding.top >= 0 && | |
bounding.left >= 0 && | |
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) && | |
bounding.right <= (window.innerWidth || document.documentElement.clientWidth) | |
); | |
}; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.scss', ], | |
}) | |
export class AppComponent implements OnInit { | |
readonly HEADER_OFFSET = -70; | |
readonly SCROLL_DELAY = 200; | |
constructor( | |
private router: Router, | |
@Inject(PLATFORM_ID) private platformId: any | |
) { } | |
ngOnInit() { | |
this.router.events.subscribe((event: Event) => { | |
if (event instanceof Scroll && event.anchor && isPlatformBrowser(this.platformId)) { | |
setTimeout(() => { | |
const targetElement = document.querySelector('#' + event.anchor); | |
if (!targetElement) { | |
window.scrollTo(0, 0); | |
} else if (!isInViewport(targetElement)) { | |
targetElement.scrollIntoView(); | |
window.scrollBy(0, this.HEADER_OFFSET); | |
} | |
}, this.SCROLL_DELAY); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment