File tree Expand file tree Collapse file tree 2 files changed +12
-4
lines changed Expand file tree Collapse file tree 2 files changed +12
-4
lines changed Original file line number Diff line number Diff line change @@ -19,16 +19,25 @@ export class HeaderTagManager {
19
19
private readonly _document = inject ( DOCUMENT ) ;
20
20
21
21
/**
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.
24
24
*
25
25
* The function behave invariably and will always point to angular.dev,
26
26
* no matter if it's a specific version build
27
27
*/
28
28
setCanonical ( absolutePath : string ) : void {
29
29
const pathWithoutFragment = this . _normalizePath ( absolutePath ) . split ( '#' ) [ 0 ] ;
30
30
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
+ }
32
41
}
33
42
34
43
private _normalizePath ( path : string ) : string {
Original file line number Diff line number Diff line change 3
3
< head >
4
4
< meta charset ="utf-8 ">
5
5
< title > Angular Material UI Component Library</ title >
6
- < link rel ="canonical " href ="https://material.angular.dev ">
7
6
< base href ="/ ">
8
7
9
8
< meta http-equiv ="Content-Type " content ="text/html; charset=utf-8 ">
You can’t perform that action at this time.
0 commit comments