Is it possible to import SVG files and inline them in Angular?

Behold, an SVG Circle:

<svg viewBox="0 0 104 104">
  <circle cx="52" cy="52" r="50" stroke="#003EFF" stroke-width="4" fill="#00FF98" />
</svg>

The Angular Project imports it in this manner:

import circle from './circle.svg';

Then, it is added to a div element like this:

<div [innerHTML]="svg" style="width:400px"><div>

However, it appears that Angular's XSS protection is stripping the content. Is there a workaround for this issue?

An attempt was made using the DomSanitizer instance like this:

  constructor(private sanitizer: DomSanitizer) {
    this.trustedCircle = sanitizer.bypassSecurityTrustUrl(this.svg);

But unfortunately, it was not successful.

Answer №1

Utilizing Angular Material has been incredibly useful for me:

import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';

Within the constructor:

constructor(
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer
) { }

To add an icon or image in the ngInit method:

    this.matIconRegistry.addSvgIcon(
        'some-icon',
        this.domSanitizer.bypassSecurityTrustResourceUrl(
            '../img/some-icon.svg'
        )
    );

And then you can use it in your HTML like this:

        <mat-icon
            svgIcon="some-icon"
            class="icon-class"
            aria-label="some-icon">
        </mat-icon>

Answer №2

Resolved the issue for you. Give it a try and see if it works.

import { Component } from '@angular/core';
import { DomSanitizer
} from '@angular/platform-browser';
import circle from './circle.svg';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  trustedCircle;
  constructor(private sanitizer: DomSanitizer) {
    this.trustedCircle = this.sanitizer.bypassSecurityTrustHtml(circle);
  }
}

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

Error: The iOS 14.2 system is unable to locate the variable "webkit."

Currently, I am developing a web application using AngularJS 1.7. The app runs smoothly on Safari with iOS versions 12, 14.0, and 14.1. However, upon upgrading my iOS to version 14.2/14.3 (tested on both), I encountered the following error: Error: Referen ...

How can I detect when an image is loaded in a specific container division using jQuery?

I have a container with multiple images inside, and I would like to capture an event each time an image finishes loading. For example: <div id="container"> <img src="..." /> <img src="..." /> <img src="..." /> ...

Unable to retrieve $wpdb, returning as null

In my development process, I am working on a basic plugin using the Wordpress Plugin Boilerplate. I have implemented AJAX to create an action triggered by a button press to remove an item from a custom database table I have set up. The AJAX function, butto ...

Can you explain the steps to implement this feature in a modal window using jQuery?

My HTML list contains a bunch of li elements. ul li img .det li I am looking to create a modal popup that appears when I click on something. I want this modal popup to have previous and next buttons, preferably implemented using jQuery. I have alr ...

Utilize the function specified in an external file

In my project, I have a typescript file named "menuTree.ts" which compiles to the following JavaScript code: define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Menu ...

The error callback for Ajax is triggered even though the JSON response is valid

Within my JavaScript file, I am making the following call: $.ajax({ type: "POST", dataType: "application/json", url: "php/parseFunctions.php", data: {data:queryObj}, success: function(response) { ...

Order of execution behavior

I am currently working on a function that, when triggered, will populate the webpage with dynamic tiles. These tiles retrieve data from a remote database through an AJAX request and utilize jQuery 3.0 in the implementation. Function Implementation: funct ...

Exploring ways to retrieve checkbox values instead of boolean values upon submission in Angular

I am currently working with a template-driven form and facing an issue. Despite receiving true or false values, I actually need to retrieve the value of checkboxes. <form #f = "ngForm" (ngSubmit) = "onClickSubmit(f.value)"> ...

Are JS commands enough for using Node.js dom APIs like jsdom and cheerio, or do I have to rely on jQuery for these tasks?

Is there a DOM API available for Node.js that allows me to use pure JavaScript commands? I prefer not to use jQuery as I already have existing code in vanilla JS. ...

Unlocking the ability to retrieve data generated by the context within getServerSideProps beyond its boundaries (for transitioning from Create React App to Next.js)

I am currently utilizing Create React App for my react application but I am in the process of migrating to Next.js. Accessing URL data such as host, protocol, and query parameters has posed a significant challenge. After some trial and error, I realized t ...

Exploring the money library in typescript after successfully installing it on my local machine

I've been struggling to set up a new library in my TypeScript project for the first time, and I can't seem to get it functioning properly. The library in question is money. I have downloaded it and placed it in the root of my project as instructe ...

Guide to incorporating Moengage into Node.js APIs for delivering email notifications based on user interactions

How can Moengage be integrated into Node Js APIs for sending notifications to users based on user events? I have reviewed the Moengage API documentation but did not find relevant information on integrating Moengage with Node Js APIs. Is there a step-by-s ...

Choose All Box for Dynamic Tables in AngularJS

Hi everyone, I'm currently working on adding a select-all checkbox to the top of my list of checkboxes using a custom directive. I found some guidance on how to do this in a thread that I came across: https://github.com/lorenzofox3/Smart-Table/issues/ ...

center a horizontal line using StyledSheets in your project

After drawing a horizontal line, I noticed that it is positioned towards the left side of the screen. I am hesitant to increase its width. Are there any other methods to move it to the center? I attempted wrapping it with another view and using alignConten ...

Resizing tables dynamically using HTML and JavaScript

I am attempting to reproduce the functionality demonstrated in this example When dealing with a large table, I want it to resize to display 10 entries and paginate them accordingly. The only thing I require is the pagination feature without the search bar ...

Invoke numerous HTTP requests and receive multiple observables in response

When attempting to call multiple HTTP requests and combine several observables into one, I am facing an issue where only the last one is being emitted. I have an input field with a form control called "ctl" where users can input a keyword to search for cus ...

When using React and React Router v6, make sure to implement a 404 status code response for unmatched routes

When it comes to managing unmatched routes with React Router, I have a solid understanding: <Routes> {/* Public routes */} <Route exact path="/" element={<Home />} /> // Other routes... {/* Error routes */} ...

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

What is the best way to store JSON encoded items in an array using square brackets?

Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue whe ...

Incorporating Hyperlinks into Text using React I18next

I'm facing an issue with I18next. I can't seem to make links to websites work correctly using the following code: import React, { Suspense } from "react"; import i18n from "i18next"; import { initReactI18next, useTranslation, ...