6

Here I'm trying to change the image svg color.

  <button>
 <img src="someImage.svg">
 </button>

Is it possible to change the color of the svg image in the button in angular 5

Waruyama
  • 3,267
  • 1
  • 32
  • 42

2 Answers2

8

You can apply CSS to your SVG if the SVG is inline in the DOM. The easiest way to achieve this is with an SVG injector. It uses Javascript to load an external SVG file and replace an HTML element (usually an <img> element) with the SVG markup.

If you use SVGInject ( https://github.com/iconfu/svg-inject/ ) your HTML will look like this:

<button>
  <img src="someImage.svg" onload="SVGInject(this)">
</button>

The onload attribute does the magic by replacing the <img> element after the image is loaded. It should look the same, but you will be able to apply CSS to the SVG.

Waruyama
  • 3,267
  • 1
  • 32
  • 42
  • unfortunately, `` does not support the `alt` attribute, which can be catastrophic to your document outline (seo). at time of writing, (1) svg `currentColor` is ignored when used via `` (2) `` is not a suitable replacement for `` due to lack of alt-text (3) thus there is no good way to utilize SVGs where you need to set their colors (4) inline SVGs are a serious source of bloat, they cannot be referenced, but instead must be horrifically duplicated. (IN CONCLUSION) SVG's totally suck and there's no good workaround – ChaseMoskal Dec 04 '20 at 00:03
  • @ChaseMoskal I just had an idea, which may improve things a little bit. How about dynamically loading an SVG, adjusting the colors, and then creating an image element from this? The document will then again contain `img`elements. This will at least solve the `alt` issue. I will check if this works. – Waruyama Dec 04 '20 at 10:05
0

I took some code from: http://www.petercollingridge.co.uk/tutorials/svg/interactive/javascript/ You have to use the object element instead of the img element. You have to give your object element an id (in the example it is "svg-object"). You have to give the button inside your svg file an id (in the example it is external-1). Then you can change the style

var svgObject = document.getElementById('svg-object').contentDocument;
var svg = svgObject.getElementById('external-1');
svg.style.fill = "green"

Inlining your svg is a little easier, but it can be done.

aptriangle
  • 1,395
  • 1
  • 9
  • 11