Angular, change the favicon dynamically using SVG images
Some applications require to inform the user when a status change. Very often these app use the title of the browser app to show some changes.
In our case we want to update the title and the favicon of the application. For the favicon we won’t use a ‘standard’ .ico but a more flexible ‘.svg’.
Change the title of the browser tab using Angular
This is pretty easy, Angular gives us an out-of-the-box Service to update the title of the browser.
The feature is so well documented that we won’t extend the information already provided in Angular.io.
As quick reference here you can find the example’s code:
export class AppComponent {
public constructor(private titleService: Title) { }
public setTitle(newTitle: string) {
this.titleService.setTitle(newTitle);
}
}
This Title service is provided in the platform-browser package. In the same package, we can find the Meta service that allows us to interact with the <meta>
tags present in the <head>
of the webpage.
Unfortunately, Angular doesn’t provide any service for the interaction of the <link>
tags.
Change the FavIcon dynamically using SVG
We want to update the favicon according to the status/value of some elements in our application.
For example, with the value less than 10 the icon is green …
… and with a value over 10 the icon has to be red
These values probably don’t mean a lot for you but for people with Type 1 Diabetes, these values are important.
Add the icons to the application
In our case, we add the icons directly in the assets of the application, if you prefer you can load them from an external URL in place of an internal link. The size of our icons is small and won’t have a big impact on the loading time. Four our application we added 4 SVG: gray, green, red and yellow.
Change the application <head>
In the <head>
of the index.html
page we add a <link>
that references the gray icon inside the assets folders.
<link rel="icon" type="image/x-icon" href="favicon.ico" sizes="any"> <!-- for browser that cannot handle SVG -->
<link rel="icon" id="favIcon" type="image/svg+xml" href="assets/icons/gray-circle.svg" sizes="any">
We leave the default link for favicon.ico in case some browsers don't support the SVG format for this use case.
We add an id
to our link to be able to refer the tag inside of the Angular code.
Angular code
Our Angular code has really nothing magical
let favIcon: HTMLLinkElement = document.querySelector('#favIcon');
favIcon.href = `assets/icons/${this.status}-circle.svg`;
When the status of our data changes we use Document.querySelector
to get a reference to the DOM Link Element that contains our SVG image.
We simply reassign the reference to a different image inside our assets. We use string interpolation to generate the filename of the image according to the state of the data. If you want to link an external image you can replace the assets link with an URL, e.g.: favIcon.href = ‘https://my-magical-website.com/images/icon.svg'