Skip to content

Instantly share code, notes, and snippets.

@UplandsDynamic
Last active August 23, 2017 10:15
Show Gist options
  • Save UplandsDynamic/8cea300ebbfdeb36e763cd10da455ff5 to your computer and use it in GitHub Desktop.
Save UplandsDynamic/8cea300ebbfdeb36e763cd10da455ff5 to your computer and use it in GitHub Desktop.
How to scroll to a fragment in Angular.io (scroll to anchor)
import { Component, OnInit } from '@angular/core';
import { OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
@Component({
selector: 'scroll-to-anchor-example',
template: `<a type="button" md-button class="button" routerLink="/this-view-url"
fragment="test-fragment" routerLinkActive="active">Go to test fragment</a>
<p>Blah blah blah ...</p>
...
<h2 id="test-fragment">Test Fragment</h2>
<p>blah blah blah ...</p>`,
styleUrls: ['./scroll-to-anchor-example.component.css']
})
export class UsageComponent implements OnInit {
private scrollSubscription: Subscription;
constructor(private router: Router) {
this.scrollSubscription = router.events.subscribe(s => {
if (s instanceof NavigationEnd) {
const tree = router.parseUrl(router.url);
if (tree.fragment) {
const element = document.querySelector('#' + tree.fragment);
if (element) { element.scrollIntoView(true); }
}
}
})
}
ngOnInit() {
}
public ngOnDestroy() {
this.scrollSubscription.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment