Css – How to change the color of an svg element in Angular

angularcss

I need to load, display and dynamically change the color of an SVG image in my Angular project by applying different CSS classes to it.

This question didn't help, since it makes use of the Modernizr library and I would like to avoid it. I don't want also to copy the d field in the path tag of the image I have directly in the html file of the Angular project because it would be a wall of text that I'm not willing to accept. I can accept instead the usage of an external dedicated library to achieve the correct outcome, like the ng-inline-svg, which I tried to use the following way:

<div class="svg1" aria-label="My icon"
   [inlineSVG]="'./assets/images/icons/ApplyIcon.svg'">
</div>

Defying the following CSS class:

.svg1 {
  color: green;
}

It loads the image perfectly as a regular img tag but if I try then to apply a custom class to it to change the image color, it doesn't work.

Furthermore, I tried to use the object tag the following way:

<div class="col-2">
    <object
       id="svg1"
       data="./assets/images/icons/ApplyIcon.svg"
       type="image/svg+xml">
    </object>
</div>

But, again, if I apply a class to the object tag with the CSS directives color: green; or fill: green; nothing would change. Any idea to achieve what I want?

Best Answer

Use the svg element in component.html file and use [ngClass] directive to dynamically change the inner svg class based on the conditions.

example:

component.ts

data.state = "New" || "In-Progress" || "Completed" // this changes dynamically based on the data

component.html:

<svg <circle class="cls-3" [ngClass] = "{'New': 'blue', 'In-Progress':'orange','Completed':'green'}[data.state]" cx="8.21" cy="8.01" r="2.44" transform="translate(-3.22 8.89) rotate(-48.73)"/></svg> // inner class of svg element

component.css:

.blue {
    fill:blue
}
.orange{
   fill: orange
}
.green {
   fill: green
}