Skip to content

Commit 45f7f49

Browse files
authored
docs: insert canonical link dynamically (#31830)
* docs: delete static canonical link * docs: insert, not update dynamic canonical link * docs: always append tag when inserted
1 parent 54f641e commit 45f7f49

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

docs/src/app/shared/header-tag-manager.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,25 @@ export class HeaderTagManager {
1919
private readonly _document = inject(DOCUMENT);
2020

2121
/**
22-
* Sets the canonical link in the header.
23-
* It supposes the header link is already present in the index.html
22+
* Sets the canonical link in the header. If the link already exists,
23+
* it will be updated. Otherwise, a new link will be created and inserted.
2424
*
2525
* The function behave invariably and will always point to angular.dev,
2626
* no matter if it's a specific version build
2727
*/
2828
setCanonical(absolutePath: string): void {
2929
const pathWithoutFragment = this._normalizePath(absolutePath).split('#')[0];
3030
const fullPath = `${MAT_ANGULAR_DEV}/${pathWithoutFragment}`;
31-
this._document.querySelector('link[rel=canonical]')?.setAttribute('href', fullPath);
31+
let canonicalLink = this._document.querySelector<HTMLLinkElement>('link[rel=canonical]');
32+
33+
if (canonicalLink) {
34+
canonicalLink.setAttribute('href', fullPath);
35+
} else {
36+
canonicalLink = this._document.createElement('link');
37+
canonicalLink.setAttribute('rel', 'canonical');
38+
canonicalLink.setAttribute('href', fullPath);
39+
this._document.head.appendChild(canonicalLink);
40+
}
3241
}
3342

3443
private _normalizePath(path: string): string {

docs/src/index.html

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
<head>
44
<meta charset="utf-8">
55
<title>Angular Material UI Component Library</title>
6-
<link rel="canonical" href="https://material.angular.dev">
76
<base href="/">
87

98
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

0 commit comments

Comments
 (0)