Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: transclusion, set color of SVG element

Tags:

css

sass

angular

I have a component.html that transcludes my svg component:

<masterflex-sidebar>
    <masterflex-logo sidebar-logo color="white">

    </masterflex-logo>
</masterflex-sidebar>

My logo.ts file:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'masterflex-logo',
  templateUrl: './masterflex.component.html',
  styleUrls: ['./masterflex.component.scss']
})
export class MasterflexComponent implements OnInit {

  @Input() color:string

  constructor() { }

  ngOnInit() {
  }

}

My svg component(part of it):

<svg 
    version="1.1" 
    xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    x="0px" y="0px"
    viewBox="0 0 237.4 35.9"
    height="35.9"
    width="237.4"
    xml:space="preserve" *ngIf="color">

I want to be able to change the color of my svg component to whatever color I want (set in my first component with color="white") and have that color apply to my svg. Is there a way to pass that color attribute into a scss style?

like image 372
Snorlax Avatar asked Feb 15 '18 18:02

Snorlax


1 Answers

An SVG element has a stroke and a fill color. You can set each one with the corresponding element or style attribute:

<svg [attr.stroke]="color" ... >
<svg [style.stroke]="color" ... >
<svg [attr.fill]="color" ... >
<svg [style.fill]="color" ... >

The color input property of the component must be set in the parent component:

<my-svg-component [color]="myCustomColor" ...>

You can try the code in this stackblitz. Please note that if shape and text elements inside of the SVG element set their own stroke or fill colors, these will override the color set at the SVG element level.

like image 172
ConnorsFan Avatar answered Sep 27 '22 20:09

ConnorsFan