How to modify CSS style in SVG using Angular2?

I have been working on adding SVG to an Angular2 component's template and I've encountered some challenges. Here is the code snippet I am using:

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

To dynamically add CSS style, I have tried various methods to access the SVG content:

1)

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

The console displays: [ ]

2)

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

The console shows: null

My Question:

I need assistance in accessing SVG content and changing CSS styles in TypeScript. Can anyone provide guidance on this matter?

Answer №1

In this scenario, there are a couple of issues that need to be addressed. Firstly, it is important to note that not using an inline SVG may restrict your ability to modify the styling attributes of the SVG element, as highlighted in this discussion on Stack Overflow. This limitation does not stem from Angular itself.

To work around this issue effectively within an Angular environment, one suggestion would be to create a dedicated component that includes the complete SVG content within its HTML:

svg-component.html

<!-- The contents of svg-component.html, where certain properties of the SVG are bound -->
<svg.... [style.fill]="color"/></svg>

In the corresponding TypeScript file, svg-component.ts:

// Within svg-component.ts, properties can be mapped to inputs for ease of use
import { Component, OnInit, Input } from '@angular/core';

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

Usage example:

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

Additionally, you might consider adopting the strategy employed by icon libraries and creating a custom font. However, unless you have an extensive collection of icons and specifically require the functionality offered by CSS properties associated with fonts, this approach may not be the most practical choice.

Answer №2

You have the ability to directly insert the svg into your code.

html:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px">
  <g>
    <path id="myId" d="..."/>
  </g>
</svg>

css:

#myId {
  fill: red;
}

typescript: Using Jquery is an option.

import $ from 'jquery';

this.el = $("#myId");

EDIT:

As mentioned in the comments below, you can also utilize document.getElementById("myId") without importing jquery.

Answer №3

It appears that this question is missing crucial information and may be approaching the situation from an XY Problem perspective. In Angular template, it's recommended to utilize the templating system and property binding instead of directly manipulating elements with DOM methods.

If you're unsure about what CSS styles to add, here are some general examples:

Option 1

Utilize the [ngClass] binding to modify a single class.

Template:

<object type="image/svg+xml"
        data="kiwi.svg"
        [ngClass]="kiwiClass">
  Kiwi Logo
</object>

Component:

// Assign as required
kiwiClass = "logo";

Option 2

Use [ngClass] to control the state of a small class list

Template:

<object type="image/svg+xml"
        data="kiwi.svg"
        class="logo"
        [ngClass]="{'red': shouldBeRed, 'blue': checkShouldBeBlue()}">
  Kiwi Logo
</object>

In your stylesheet, define the styles for the .red and .blue classes, along with the conditions for shouldBeRed and shouldBeBlue.

The [ngClass] values can evaluate to boolean expressions, including functions.

Option 3

Employ [class.className] to manage the state of a small class list

Template:

<object type="image/svg+xml"
        data="kiwi.svg"
        class="logo"
        [class.red]="shouldBeRed"
        [class.blue]="checkShouldBeBlue()">
  Kiwi Logo
</object>

For assigning styles and conditions, follow the same approach as in option 2.

Check out this informative resource on utilizing SVG with Angular 2+.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the signs that indicate whether a parameter is an enum or an array of enums?

I am looking to pass either a single enum value or an array of enum values to a function. In order to achieve this, I have created a custom function: export enum SettingType { hairColors ='haircolors', hatSizes = 'hatsizes' } publi ...

How to retrieve the data from a PHP file using Angular 4 CLI?

Is there a way to retrieve the response from a PHP file using Angular 4? If the PHP file is placed in the assets folder, the GET request will identify the file and proceed to download its content. For example: headers: Headers ok: true status: 200 status ...

Upgrading from Angular 10 to 13 resulted in an error that required adding 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas'. Although this fix was implemented, the issue still persists and the application remains broken

Here are a few examples of errors: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurred in the template of component ShochatactivestreamviewShellComponent. Error: src/app/money_makers/shochat_guts/shochat_content_creato ...

Utilizing Angular 2 for transforming JSON data into Angular classes

I have been working through the Angular2 getting started guide to kickstart my own application development. So far, I have managed to retrieve JSON objects from a local file and display them in angular2 templates. However, the challenge arises when the str ...

The attribute 'xxx' is not found within the 'Readonly<{}>' type

I am currently in the process of writing tests for a React Typescript component. App.tsx: import * as React from 'react'; import { Button } from 'react-bootstrap'; interface Igift { id: number; } interface IAppState { gifts: Igi ...

Setting up Angular universal web configuration with SSL and automatic redirection to the www subdomain

I'm facing an issue with the web.config file in my Angular Universal project. Here is a snippet of my web.config file: <configuration> <system.webServer> <!-- indicates that the server.js file is a node.js application to be ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

Sharing information between components in React JS

Hello everyone, I'm facing a simple problem with two "Components" in React JS. The first one is App.js and the other one is Botones.js. App.js imports Botones.js. In App.js, I have a "NavBar", an Input Text, and a Button for SignIn, like this: https: ...

I cannot access the 'isLoading' state in React Query because it is undefined

Since updating to the latest version of react query, I've been encountering an issue where the 'isLoading' state is returning undefined when using useMutation. Here's the code snippet in question: const useAddUserNote = (owner: string) ...

Are there any simple methods for streaming HLS Video in a React application that are not resource-intensive?

At the moment, my React Typescript application is set up to stream HLS video using the .m3u8 file format. Originally, we relied on the videojs library for this task, but switched to React-Hls-Player in order to reduce our application's bundle size. Wh ...

There was an issue thrown during the afterAll function: Unable to access properties of undefined

Recently, I upgraded my Angular project from version 15 to 15.1 and encountered an error while running tests. To replicate the issue, I created a new Angular 15.1 project using the CLI and generated a service with similar semantics to the one causing probl ...

The Angular NgForm method form.resetForm does not seem to be resetting properly when dealing with arrays

I encountered an issue with my simple ngForm that was previously functioning well with string input and single select dropdowns. When I added a multi-select dropdown that introduces an array, I started facing a strange problem. Even after using form.formRe ...

Setting up a variable with no operation assigned to it

As I delved into the Angular utils source code, I stumbled upon this interesting line: export const NOOP: any = () => {}; It seems pretty straightforward - a variable that doesn't perform any operation. But then, within the same library, there is ...

How to use Angular pipes to format dates as Long Dates in the template

Suppose I have a date input such as 2022-04-02T00:00:00. When I utilize {{data?.dateStarted | date:'MM/dd/YYYY'}}, the result will be 04/02/2022. But how can we transform it into a Long Date format like April 2, 2022? Does anyone have any sugges ...

Is the Angular CLI proxy configuration failing to work properly?

Working on Angular CLI (ng4) and facing an issue with the proxy configuration for a rest api call outside the application. While running ng build --prod --aot=true, I encounter a 404 status code. However, it works fine in development mode. How can I resol ...

The Angular 2 router encounters issues with reusing a Component instance when navigating to the same route with varying parameters

Based on the information provided in Angular 2 documentation: The default behavior of the router is to reuse a component instance when navigating to the same component type without visiting a different component first. However, the parameters may change ...

Listener of events calculates the outcome

In need of help with retrieving the current coordinates of a clicked point on Google Maps. Here is my code snippet: let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); getCoords() { google.maps.event.addListener ...

Why are the tabs in Angular displaying differently when the tab titles exceed 8 characters with Bootstrap 5?

Angular 14 Bootstrap 5 I developed a custom tabs component with pipes between the tabs that works flawlessly. However, I encountered an issue where the tabs slightly shift when the tab title exceeds 8 characters. Despite my efforts, I cannot pinpoint the ...

Having trouble installing npm packages due to an error

As I attempt to install my npm packages, a frustrating error occurs. What steps should I take to resolve this issue? npm ERR! code EINVALIDTYPE npm ERR! typeerror Error: Argument #5: Expected object but got string npm ERR! typeerror at inflatableChild ...

There has been a mistake: "Unable to locate a suitable differ supporting object '[object Object]' of type 'object'. NgFor is only able to bind to Iterables like Arrays."

Currently facing an issue: I am trying to extract the values of "place" using ngFor directive. Here's what I have implemented: .html <ng-container *ngFor="let se of List" Here is the JSON data: .json "place": [ { &qu ...