How to update Favicon in Your Angular Application dynamically
Favicons are a small but essential part of web applications, providing a visual cue that represents your website in the browser tab. Here is an example of favicon from Microsoft website.
In a typical Angular application, favicons are located under src
folder.
And included in index.html
file.
<link rel="icon" type="image/png" href="favicon.png">
Setting favicon dynamically
While setting a static favicon is straightforward, there may be scenarios where you want to dynamically update the favicon based on user input. For example, “Branding” or “Multi-tenancy” feature for SaaS products where a tenant wants to provide branding assets like company logo and favicon.
You might have a BrandinService
fetching tenant specific branding information and emit an event whenever user update favicon.
private getBranding() {
this.brandingService.brandingChanged.pipe(
takeUntil(this.destroy$)).subscribe(branding => {
this.branding = branding;
this.setFavicon(branding);
});
}
To update favicon, we need to create an HTML link
element if it doesn’t exist and set the href
property with user provided faviconUrl
.
private setFavicon(branding: BrandingEntry) {
this.faviconElement = document.querySelector<HTMLLinkElement>('link[rel*="icon"]');
if (!this.faviconElement) {…