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

I incorporated a CSS file from another HTML document. What do you think about that?

In my work with Ionic 3 and angular 4, each HTML file is accompanied by its own CSS file. There are times when I reference a class in one HTML file that is defined in another HTML file. I have observed that this CSS class gets injected into the main.js He ...

Obtain the dimensions (width and height) of a collection of images using Angular and TypeScript

Currently, I am facing an issue with my image upload functionality. My goal is to retrieve the width and height of each image before uploading them. However, I've encountered a problem where my function only provides the dimensions for the first image ...

During the evaluation of an Angular application, an examination was conducted on the feature where clicking a button would increase a count and show the result in an h2 element

After clicking a button, the count is supposed to increase and the updated count should be displayed on the HTML page using Angular. I have written a test for this scenario using Jasmine + Karma runner, but the expected value is not matching. During testi ...

Issue with Angular *ngIf not rendering properly following retrieval of data from API

I am experiencing an issue with the *ngIf directive. When I retrieve my data in the AppComponent and utilize *ngIf, my Revolution Slider does not display. Without using ngIf When using ngIf This is how my code appears: Service.ts getAllPlaces(languag ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

ControlValueAccessor can automatically detect when the required property is enabled on a reactive form

Is there a way to detect within a custom control, that implements ControlValueAccessor and is exclusively utilized with reactive forms, when the required validator has been added or removed? I am looking for an alternative solution instead of creating an ...

What is the best way to toggle the visibility of the ng-bootstrap datepicker-popup component?

Is there a way to toggle the visibility of the ng-bootstrap datepicker-popup by setting a property to 'true' or 'false'? In my form, I have the following snippet and I only want to show the entire div section if the user chooses to inp ...

Utilizing Angular to call a function defined in Renderer2 and assign it to a

In my directive, I have configured a table value to be replaced by an anchor tag using the renderer.setProperty method. The anchor tag is enhanced with a "click" attribute that I am unsure how to interact with: either through accessing the function "onCli ...

Setting up Typescript error handling for next-auth getProviders configuration

I recently started learning Typescript and came across a tutorial using next-auth. However, I encountered an error while following the tutorial with Typescript when using the getProviders function. https://i.stack.imgur.com/H5LaL.png https://i.stack.imgu ...

Angular Material Table with Pagination: Fetch data from server by triggering API call upon clicking on the "Next Page

When working with MatPaginator in conjunction with mat-table, what is the most effective approach for handling the next page click event? I have developed a custom DataSource with connect() and disconnect() functions. Is it necessary to explicitly manage ...

Problem with connecting Angular data

<body ng-app="myAPP"> <div ng-controller="employeeCtrl"> <table style="border:1px solid gray"> <tr> <th>Employee Name</th> <th>Employee Address</th> <th> ...

Is there a disparity in capabilities or drawbacks between ViewChild and Input/Output in Angular?

As I delve into Angular ViewChild and compare it to Input/Output parameters, I can't help but wonder if ViewChild has any drawbacks or limitations compared to Input/Output. It appears that ViewChild is the preferred method, as all parameters are now ...

React Bootstrap Forms: The <Form.Control.Feedback> element is failing to display when the validation is set to false

Problem: I am facing difficulties with displaying the React Bootstrap <Form.Control.Feedback></Form.Control.Feedback> when the validation is false in my form implementation. Steps to Recreate: Upon clicking the Send Verification Code button, ...

The initial execution of the "ionViewDidEnter" method in Ionic 2 can be quite sluggish

Could you explain to me why there is a significant delay in loading the below functionality for the first time, but it loads normally on the second attempt? The same delay occurs on the actual device as well. Please refer to the attached video. Note : The ...

Angular HTML is throwing an error related to object arrays

Is there a way to display only specific fields of an array? <div class="form-check" *ngFor="let periodo of filterPeriodos()"> <div>{{periodo.periodos | json}}</div> <input class="form-check-input mr- ...

Are optional parameters in TypeScript distinct from parameters that have the ability to be undefined?

Is there a distinction between the following two code snippets? function sayHello(name?: string) { if (name) { return 'Hello ' + name; } return 'Hello!'; } and function sayHello(name: string | undefined) { if (name) { return &apo ...

Implementing Angular 4 to fetch information from a JSON file

As a beginner in Angular, my current task involves loading data from a JSON file upon click, which I have successfully achieved so far. However, I am facing an issue where I'm unable to load the first JSON object before clicking, meaning that I want ...

The type 'void | Observable<User>' does not include the property 'subscribe'. Error code: ts(2339)

authenticate() { this.auth.authenticate(this.username, this.password).subscribe((_: any) => { this.router.navigateByUrl('dashboard', {replaceUrl: true}); }); } I'm puzzled by this error message, I've tried a few solu ...

How to reference an array from one component to another in Angular 2

Within my AddUserComponent, I have a public array declared like this: public arr: Array<any> = [] This array stores the names of users. Now, I need to access these values in another component called AddTopicComponent in order to display the user&a ...

Is there a way to stop the BS modal from appearing when I hit Enter after filling out a form?

Currently, I am implementing a form within an Angular framework. Every time I press the Enter key in any input field, it triggers the opening of a bsmodal dialog. ...