Skip to content

Commit 78b92ab

Browse files
committed
fix(docs): enable fragment navigation and anchor linking (#3291)
1 parent 8f7a101 commit 78b92ab

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/app/app.component.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
22
import { Meta, Title } from '@angular/platform-browser';
33
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
4+
import { ViewportScroller } from '@angular/common';
45
import { filter } from 'rxjs/operators';
56
import { HOMEPAGE_TITLE, TITLE_SUFFIX } from './constants';
67

@@ -17,6 +18,7 @@ export class AppComponent implements OnInit {
1718
private readonly metaService: Meta,
1819
private readonly router: Router,
1920
private readonly activatedRoute: ActivatedRoute,
21+
private readonly viewportScroller: ViewportScroller,
2022
) {}
2123

2224
async ngOnInit() {
@@ -25,6 +27,7 @@ export class AppComponent implements OnInit {
2527
.subscribe((ev: NavigationEnd) => {
2628
this.updateTitle();
2729
this.updateMeta(ev);
30+
this.handleFragmentScroll(ev);
2831
});
2932
}
3033

@@ -58,4 +61,20 @@ export class AppComponent implements OnInit {
5861
this.robotsElement = undefined;
5962
}
6063
}
64+
65+
private handleFragmentScroll(event: NavigationEnd) {
66+
const fragment = event.url.split('#')[1];
67+
if (fragment) {
68+
setTimeout(() => {
69+
const element = document.getElementById(fragment);
70+
if (element) {
71+
const offsetTop = element.offsetTop - 100;
72+
window.scrollTo({
73+
top: offsetTop,
74+
behavior: 'smooth'
75+
});
76+
}
77+
}, 100);
78+
}
79+
}
6180
}

src/app/shared/components/toc/toc.component.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,13 @@ export class TocComponent implements OnInit, OnDestroy, OnChanges {
103103
}
104104

105105
navigateToAnchor($event: MouseEvent, elementRef: HTMLElement) {
106+
$event.preventDefault();
106107
if (elementRef) {
108+
const offsetTop = elementRef.offsetTop - this.scrollTopOffset;
109+
window.scrollTo({
110+
top: offsetTop,
111+
behavior: 'smooth'
112+
});
107113
this.findCurrentHeading();
108114
}
109115
}

0 commit comments

Comments
 (0)