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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With