Skip to content

Instantly share code, notes, and snippets.

@martine-dowden
Last active October 11, 2017 08:30
Show Gist options
  • Save martine-dowden/c49bda028bf5115341ae553789d404e6 to your computer and use it in GitHub Desktop.
Save martine-dowden/c49bda028bf5115341ae553789d404e6 to your computer and use it in GitHub Desktop.
Angular 4 navigating to top of page or to hash depending on the route
import { Component, AfterContentChecked, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterContentChecked, OnDestroy {
public currentRoute;
private sub;
constructor(public router: Router, public route: ActivatedRoute) {}
ngAfterContentChecked() {
// Because angular still doesn't support linking to a hash in the page...
// Does my new route have a hash?
const match = this.router.url.match(/(^.*)\#/);
// if hash
if (this.router.url !== this.currentRoute && match) {
this.sub = this.route.fragment.subscribe(f => {
const element = document.querySelector('#' + f);
if (element) {
element.scrollIntoView();
}
});
// check to see if routes are identical
} else if (this.router.url !== this.currentRoute) {
// routes are not the same, scroll to top of page
document.getElementById('container').scrollTop = 0;
}
// update current route for next go round
this.currentRoute = this.router.url;
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
// --------------------------------------------------------------------------
// In the component that has the hash
import { Component } from '@angular/core';
import { Router } from "@angular/router";
@Component({
selector: 'app-component',
templateUrl: './component.html',
styleUrls: ['./component.scss']
})
export class Component {
constructor(private router: Router) {}
scrollTo(id) {
// check for the hash
if (this.router.url.match(/(^.*)\#/)) {
const element = document.querySelector('#' + id);
if (element) {
element.scrollIntoView();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment