Skip to content

Commit 5eea3ea

Browse files
committed
fix(docs): Make fragment scrolling work
1 parent 466c39c commit 5eea3ea

3 files changed

Lines changed: 45 additions & 2 deletions

File tree

projects/ngqp-demo/src/app/demo-routing.module.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,11 @@ const routes: Routes = [
3636
imports: [
3737
RouterModule.forRoot(routes, {
3838
useHash: true,
39-
scrollPositionRestoration: 'enabled',
40-
anchorScrolling: 'enabled',
39+
// FIXME: These don't work as expected at the moment, but we can revisit activating them later.
40+
// We explicitly disable them as they will become enabled by default in the future, and as long
41+
// as we have our own solution, we need to avoid that.
42+
scrollPositionRestoration: 'disabled',
43+
anchorScrolling: 'disabled',
4144
}),
4245
],
4346
exports: [ RouterModule ],

projects/ngqp-demo/src/app/demo.component.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,29 @@
11
import { Component } from '@angular/core';
22
import { faGithub } from '@fortawesome/free-brands-svg-icons';
3+
import { FragmentScrollService } from './shared/fragment-scroll.service';
4+
import { Router } from '@angular/router';
35

46
@Component({
57
selector: 'demo-root',
68
templateUrl: './demo.component.html',
79
styleUrls: ['./demo.component.scss'],
10+
providers: [
11+
// This cannot be provided in root
12+
FragmentScrollService,
13+
],
814
})
915
export class DemoComponent {
1016

1117
public faGithub = faGithub;
1218
public isNavbarExpanded = false;
1319

20+
constructor(
21+
private fragmentScroller: FragmentScrollService,
22+
private router: Router,
23+
) {
24+
fragmentScroller.startFragmentScroller(router);
25+
}
26+
1427
public closeNav() {
1528
this.isNavbarExpanded = false;
1629
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { Injectable } from '@angular/core';
2+
import { ViewportScroller } from '@angular/common';
3+
import { NavigationEnd, Router } from '@angular/router';
4+
import { filter, map } from 'rxjs/operators';
5+
6+
@Injectable()
7+
export class FragmentScrollService {
8+
9+
constructor(private scroller: ViewportScroller) {
10+
}
11+
12+
public startFragmentScroller(router: Router): void {
13+
router.events.pipe(
14+
filter(event => event instanceof NavigationEnd),
15+
map(event => event as NavigationEnd)
16+
).subscribe(event => {
17+
const { fragment } = router.parseUrl(event.urlAfterRedirects);
18+
if (!fragment) {
19+
this.scroller.scrollToPosition([0, 0]);
20+
return;
21+
}
22+
23+
setTimeout(() => this.scroller.scrollToAnchor(fragment), 0);
24+
});
25+
}
26+
27+
}

0 commit comments

Comments
 (0)