Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: how to add/change css style in svg?

I have the following code to add svg to angular2 component's template:

<object type="image/svg+xml" data="kiwi.svg" class="logo">
  Kiwi Logo
</object>

In order to add css style on the fly, I tried several ways to get contents:

1)

public ngAfterViewInit(): void {
        this.el = this._doc.getElementsByTagName('svg');
        console.log(this.el);
    }

result in console: [ ]

2)

public ngAfterViewInit(): void {
  this.el = this._elementRef.nativeElement.querySelector('object');
  console.log(this.el);
}

result in console: null

Question:

Can anyone help me about how to access svg and how to change css style in typescript?

like image 895
Ng2-Fun Avatar asked Nov 09 '22 06:11

Ng2-Fun


1 Answers

There are two issues here: First you are not using an inline svg therefore as cited here Changing color of SVG which was embedded using <object>, so you won't be able to change the svg styles, such as the fill of the element. This is not an angular problem.

To do this in angular in a practical way I suggest creating a component which has the full svg on its html:

svg-component.html

<!-- svg-component.html, where we bind some properties of the svg-->
<svg.... [style.fill]="color"/></svg>

svg-component.ts,

// svg-component.ts, where we  map to inputs these properties for easy 
import { Component, OnInit, Input } from '@angular/core';

@Component({
 ...
})
export class SvgComponent implements OnInit {
  @Input color = '#fff'; 
  ...
}

Usage:

<svg-component color="#000"></svg-component>

.

Another idea would be to try copying the approach of icon libraries and create a font, but unless its a very large collection and you want to use fonts css properties and almost create a library I would vote against it.

like image 132
zardilior Avatar answered Nov 15 '22 07:11

zardilior