Moving SVG Module

My goal is to create a custom component that can dynamically load and display the content of an SVG file in its template.

So far, I have attempted the following approach:

icon.component.ts

...

@Component({
    selector: 'app-icon',
    template: `
        <div [innerHTML]="svgTemplate">
        </div>
    `,
})
export class IconComponent implements OnInit {
    @Input() name: string;

    private svgTemplate: string;

    constructor(
        private http: Http
    ) { }

    ngOnInit() {
        this.http.get(`assets/icon/ic_${this.name}.svg`).map(response => response.text()).subscribe(svg => {
            this.svgTemplate = svg;
        });
    }
}

However, the SVG content appears to be escaped, as nothing is showing up in the template div.

Below is an example of SVG content:

<svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 52.4 44.1" style="enable-background:new 0 0 52.4 44.1;" xml:space="preserve">
<style type="text/css">
    .st0{fill:#444444;}
</style>
<g>
    <g transform="translate(312, 312)">
        <path class="st0" d="M-259.6-312H-312v6.4h52.4V-312z"/>
    </g>
    <g transform="translate(312, 312)">
        <path class="st0" d="M-259.6-293.1H-312v6.4h52.4V-293.1z"/>
    </g>
    <g transform="translate(312, 312)">
        <path class="st0" d="M-259.6-274.3H-312v6.4h52.4V-274.3z"/>
    </g>
</g>
</svg>

Answer №1

Angular has built-in security measures that automatically sanitize HTML content, including SVG elements, if the source is considered untrusted. This process helps prevent cross-site scripting (XSS) attacks by filtering out potentially harmful code and styles.

However, if you trust the source of the SVG file, you have the option to bypass this automatic sanitization using Angular's DomSanitizer module. It's important to note that by doing so, you may be exposing your application to injection attacks. While this method can be useful when working with trusted sources, it should still be used cautiously.

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

this.svgTemplate = this.domSanitizer.bypassSecurityTrustHtml(svg);

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

Utilize the datasource.filter method within an *ngFor loop

I have a table that filters based on certain search criteria, which I implemented using the example found at: https://material.angular.io/components/table/examples Now, I am wondering if it is possible to apply this filtering functionality to an *ngFor lo ...

Is there a way to alter the date format for input elements within formGroups using Angular 7?

When the input is of type 'Date', the date format is dd/MM/yyyy. I need to convert the date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calendar). Below is the code snippet. <form [formGroup]="opportunityForm" (ngSubmit ...

NgFor in IONIC4 can only bind to Iterables like Arrays

Hello everyone, I am facing an issue in my code: it is displaying the error: (ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.) I am trying ...

Using TypeScript with Next.js getStaticProps causes errors

Currently, I am grappling with utilizing getStaticProps along with TypeScript. Initially, I attempted to achieve this using a function declaration: import { Movie } from './movies/movie' import { GetStaticProps } from 'next' export asy ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

registering a back button action in Ionic2 for multiple pages

Currently, I am in the process of developing my Ionic2 app and have encountered a dilemma regarding the functionality of registerBackButtonAction. On one page, let's call it pageA, I have implemented this function and everything is functioning as exp ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Angular module cannot be located

While working on implementing a chat feature for my project using sockJS and STOMP, I encountered several challenges with installing these two libraries. Despite attempting various methods such as installation from index.html, npm install, and manual downl ...

Retrieving properties of a universal function

I am facing a challenge in creating a class that accepts a factory function as one of its parameters in the constructor, which is then used to create instances of another class. The implementation below is written in JavaScript. // item to create class Ite ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

The error message indicated that a Promise<string> was expected, but instead a Promise<string|number> was received

Confusion Over Promise Type Error How did the TypeScript compiler generate the error message displaying Type Promise <string|number> ... in the following scenario? Type 'Promise<string | number>' is not assignable to type 'Prom ...

Utilizing the validator in Vue with the setup script, TypeScript, and the composition API

While working on some code from a tutorial, I came across the challenge of implementing a validator in a similar fashion to the example provided. My task involves utilizing the script setup, typescript, and the composition API. props: { image: { ...

Learn how to automatically access keys in local storage using Angular

I need to implement a way to store data in local storage so that it persists even when the page is refreshed. In my HTML file, there is a button that triggers a function in my TypeScript file. This function takes a parameter 'game', which is an i ...

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

Troubleshooting Issue with Angular Library: Live Reload Feature Not Functioning

In setting up my Angular workspace, I have 3 libraries and one application (with more to be added in the future). This is how the TypeScript paths are configured: "paths": { "@lib/a/*": [ "projects/libs/a/*", ...

The SunEditor onChange event does not reflect updated state information

software version next: 12.0.7 suneditor: 2.41.3 suneditor-react: 3.3.1 const SunEditor = dynamic(() => import("suneditor-react"), { ssr: false, }); import "suneditor/dist/css/suneditor.min.css"; // Import Sun Editor's CSS Fi ...

Unfortunately, the utilization of an import statement outside a module is restricted when working with Electron

Is there a solution to the well-known problem of encountering the error message "Cannot use import statement outside a module" when working with an Electron-React-Typescript application? //const { app, BrowserWindow } = require('electron'); impor ...

Confirm the existence of duplicates within an Angular reactive form

I am working with a reactive form that looks like this: https://stackblitz.com/edit/angular-form-array-example After clicking the "add credentials" button 3 times, I have 3 sets of elements for username and password. In the first row, I enter the usernam ...

Monitor modifications to documents and their respective sub-collections in Firebase Cloud Functions

Is it possible to run a function when there is a change in either a document within the parent collection or a document within one of its subcollections? I have tried using the code provided in the Firebase documentation, but it only triggers when a docume ...