There are many ways to use svg icons
in angular projects.
img
tag
You can use an img
tag:
<img src="assets/icons/my-icon.svg">
With this solution it's not a svg anymore, it's an img
. So we have caching for free but you loose the styling to change the color for example.
mat-icon
Second option, you can use the mat-icon
or something similar to inline the svg. It works fine, but for me, it add more complexity like a http call just to inline an svg icon. Also you wrap your svg with extra element and the more you are using svgs, the more you are adding extra elements.
Angular template
Third option is just copy-past your svg icon in the template and it works like magic. I found this approach the best but it still has some problems:
Which svg icon?
If we see a svg icon in the template, we can't know its visual and we don't know about it. we need to inspect to associate the visual with the code.
Code duplication
If you want to use the same svg in more than one place, you finish by duplicating code.
Both of this problems we can solve by creating a component.
A solution, but
By creating a component, we can associate a name to this svg file and we can use it everywhere. And if we don't use this component anymore thanks to Tree shaking by angular to not add it to the bundle.
Perfect, we are close to a good solution..
Final solution
But still we have one problem, the host element. The host element make it hard to style your svg and you need bypass it. If we try to style our svg from a parent container, we should be aware that the svg is not a direct child and the direct child is the host element.
To Remove the use of host element in angular we can use attribute selector
. so we can add out svg like this:
<svg class="text-blue-500 size-6" si-bird-icon></svg>
This solution bring the simplicity of inlying svgs files in angular template and ability to style it with css more easy.
But we need to create an angular component for every svg, its' hard and time consuming...
@semantic-icons
As I said, preparing svg icons to be used with attribute selector
will need time and preparation. Good news I already did that in my GitHub repo :https://github.com/khalilou88/semantic-icons, for many svg libs like lucide-icons, heroicons, tabler-icons, ...
I created a collection of free and open source icons ready for use in your angular projects. You just need to know the name of the svg and add the suffix and prefix.
The bird icon from Lucid from https://lucide.dev/icons/bird, can be added like this in your template:
<svg class="text-blue-500 size-6" si-bird-icon></svg>
Thanks for reading and see you next time.
Top comments (0)