1

I am trying to update app favicon in my angular 2 app by creating <link> tag in index.html by doing:

<head>
    <base href="/" />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link id="appFavicon" rel="icon" type="image/png" href="assets/images/teal.png"></link>
</head>

However, the transpiled DOM does not have my link tag. It deletes the <link> row.

This causes error:

core.es5.js:1084 ERROR TypeError: Cannot read property 'setAttribute' of null

when I try to update, the favicon in the app when doing something like:

this._document.getElementById('appFavicon').setAttribute('href', 'assets/images/red.png');

my component constructor has :

@Inject(DOCUMENT) private _document: any)

I have tried by using closed and non closed link tags as well:

<link id="appFavicon" rel="icon" type="image/png" href="assets/images/teal.png">

and

<link id="appFavicon" rel="icon" type="image/png" href="assets/images/teal.png"/>

I also tried to create a link element in onInit method as well, and that also does not get added to DOM.

Please suggest how to add <link> to DOM, or some alternate methods to update favicon.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Bleamer
  • 637
  • 9
  • 24
  • tag is HTML5 introduced. Have you added your code into ? – M3ghana Feb 26 '18 at 02:59
  • 1
    @M3ghana Actually, the `link` element was around in HTML 2. It is an empty element however, so there should be no `` in the HTML, just like the `meta` elements. – Heretic Monkey Feb 26 '18 at 03:08
  • If the transpiler is removing it, as you suggest, we need to know more about your build process. – Randy Casburn Feb 26 '18 at 03:12
  • Possible duplicate of [Changing website favicon dynamically](https://stackoverflow.com/questions/260857/changing-website-favicon-dynamically) – Heretic Monkey Feb 26 '18 at 03:14
  • @M3ghana, Yes I have added !DOCTYPE tag. – Bleamer Feb 26 '18 at 03:32
  • @MikeMcCaughan I am using gulp, with webpack for compiling. Anything specific that I should look at, in the build process ? The final rendered app does not have the link tag. – Bleamer Feb 26 '18 at 03:35

1 Answers1

0

This may not be the most optimal solution but I create a method to do this task:

private updateFavicon(pathToIcon: string) {
    let link: any = this._document.getElementById('appFavicon') || this._document.createElement('link');
    link.type = 'image/png';
    link.rel = 'icon';
    link.href = pathToIcon;
    link.id = 'appFavicon';
    document.getElementsByTagName('head')[0].appendChild(link);
}

I am just passing the relative path to the file to be updated as favicon.

Bleamer
  • 637
  • 9
  • 24