Dealing with DomSanitizer problem in Angular 2

When using background-image inline for my *ngFor list items, I encountered an issue. In my Component Class, I defined a variable to store a common part of the images' URLs (e.g., ) along with unique parts of the image URLs as this.image (such as qwerty/01.jpg, uiop/02.jpg, asdfg/03.jpg, and so on).

The snippet in my AppComponent looks like this:

export class AppComponent {
cartItems: any;
image: any;

constructor(public cartService: CartService, private sanitizer: DomSanitizer) { }

ngOnInit(){
let sanitizedUrl = this.sanitizer.bypassSecurityTrustUrl('http://storage.com/' + this.image);

  this.cartService.getCartItems().subscribe(
     (data) => this.cartItems = data
  );

}

In my view, where cartItem is iterated over using *ngFor:

<span class="col cart__item--imageBox" 
[style.background-image.url]="('sanitizedUrl' + cartItem.image)">
</span>

However, the console displayed warnings:

WARNING: sanitizing unsafe style value sanitizedUrl<<here go the images URLs endings - qwerty/01.jpg, uiop/02.jpg, asdfg/03.jpg, etc >> (see http://g.co/ng/security#xss).

I assumed the URL was "sanitized".

To address this issue, I updated my NgOnInit function as follows:

ngOnInit(){
let addSanitizedUrl = (cartItem) => {
      cartItem.sanitizedImageUrl = this.sanitizer.bypassSecurityTrustStyle('https://s27.postimg.org/' + this.image + cartItem.image)
      return cartItem;
    };

this.cartService.getCartItems().subscribe(
    (data) => this.cartItems = data.map(addSanitizedUrl)
});

After making these changes, the warnings disappeared. However, I am facing difficulties in finding the images passed in the service. They are not visible via DevTools Inspector.

Answer №1

Only some parts of your URL are being sanitized. To ensure complete sanitization,

You can create a method in your component for sanitizing like this:

sanitize(url:string){
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }

In your HTML, make sure to call the above method before passing the URL like so:

<span class="col cart__item--imageBox" 
[style.background-image.url]="sanitize('sanitizedUrl' + cartItem.image)">
</span>

This is just a warning and can be disregarded.

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

Having issues with installing @angular/cli globally using npm on Windows 7, the process gets stuck and does not

Encountering an issue while attempting to install the Angular CLI from npm, as it gets stuck asking to loadAllDepsIntoIdealTree. Here are the steps taken: C:\Windows\system32\node -v v6.11.1 C:\Windows\system32\npm -v 3.1 ...

Challenges with passing props to a higher order stateless component in React using Typescript

I'm having trouble creating a NavLink following the react-router tutorial. I'm not sure why it's not working with Typescript 2.1 import React from 'react'; import { Link, LinkProps } from 'react-router'; const NavLink: ...

What is the process for transforming a multi-dimensional array containing strings into a multi-dimensional array containing numbers?

I've got a unique structure of data composed of arrays with strings as seen below: [ 0: Array(1) 0: Array(6) 0: [5.379856, 43.252967] 1: [5.422988, 43.249466] 2: [5.425048, 43.245153] 3: [5.383804, 43.239 ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

I need to create a login form using Angular - what steps should I follow?

I'm currently in the process of developing a login form for my website. Utilizing angular, express, and mongoDB. Below is the login function controller I have implemented: loginUser: (req, res) => { User.findOne({ username: req.bo ...

Concealing tab bars on Ionic 2 secondary pages

In my Ionic Bootstrap configuration, I have the following setup: { mode: 'md', tabsHideOnSubPages: true } However, despite having this setting in place, the tabs still appear on some sub-pages. It seems to be happening randomly. Is there ...

Issue with the functionality of Angular reactive custom validator inoperable

Recently, I created a simple validator that compares the values of two date form controls within a form group. The basic rule is that the maturityDate has to be greater than the valueDate, otherwise the form group should be marked as invalid. Here is how ...

Can a standard tuple be matched with its corresponding key?

This code snippet showcases a function that can recognize that the key "banana" cannot have the value "red": type Fruits = { banana: 'yellow' | 'green' strawberry: 'red' } const fruit = <K extends keyof Fruits>(modu ...

The signal property 'ɵunwrapWritableSignal' is not found on the specified type 'typeof import/node_modules/@angular/core/index")'

Despite attempting the solutions provided in previous threads, none of them have been successful for me. Can someone please lend a hand with this issue? https://i.stack.imgur.com/sGRsn.png ...

Encountering a Problem on Heroku: TypeScript Compilation Error with GraphQL Files - TS2307 Error: Module 'graphql' Not Found or Its Type Declarations Missing

While trying to compile my typescript project with graphql files for deployment on Heroku, I encountered the following error message: node_modules/@types/graphql-upload/index.d.ts(10,35): error TS2307: Cannot find module 'graphql' or its correspo ...

There is a type error in the dynamic assignment in TypeScript. I have various data that need to be fetched from one another

const obj1 = { a: 1, b: "xx" }; const obj2 = { a: 2, b: "3", d: "hello" }; for (const key in obj1) { const _key = key as keyof typeof obj1; obj1[_key] = obj2[_key]; } x[_key] error Type 'string | number' is no ...

Is it possible to add animation to ngFor where the item slides in from the left only when it is within the view port?

I am working with an array containing numerous items. I have implemented ngFor to display only the first few items with a scroll feature. Each item is animated to slide from left into the view port. However, I would like this animation to apply to the bo ...

Simulating TypeDI service behavior in Jest

My current setup includes Node with TypeScript, TypeDI and Jest. I've been working on creating services that have dependencies on each other. For example: @Service() export class MainService{ constructor(private secondService: SecondService){} public ...

Looking to place a global filter outside the primeNG table component?

I am currently utilizing primeNG in my project and I have a need to incorporate a global filter. The challenge I am facing is that I must add this filter in a different component. These two components are deeply nested within other components. My approach ...

The element you are trying to access, "noUiSlider," does not belong to the type "HTMLElement" and cannot be found

Running into a roadblock here. What mistake am I making? .... /// <reference path="../../../typings/tsd.d.ts" /> var slider:HTMLElement = document.getElementById('slider'); noUiSlider.create(slider, { start: +$input.val(), step: + ...

Angular dynamically changes the placeholder text in an input based on a selection made in a mat select dropdown

Trying to change the placeholder text in a mat-input based on selection in mat-select, but struggling to bind it to the selected option. <mat-form-field appearance="outline" class="search-field" style="width:40vw"> ...

Unable to locate necessary assets, Electron encounters a resource deficiency

I'm currently developing a straightforward app using Angular and Electron. My goal is to set up the project as much from scratch as possible for the purpose of learning. Following this article, I have successfully created a basic Angular project that ...

What is the best way to customize the appearance of chosen selections in the MUI Autocomplete component?

I'm currently facing an issue with changing the style of selected options in MUI when the multi option is enabled. My goal is to alter the appearance of all highlighted options. Any assistance on this matter would be greatly appreciated, thank you! ...

Passing optional inputs in Angular using ngx-charts is a simple and convenient

Currently delving into Angular 8 and ngx-charts. My goal is to showcase graphs sourced from configuration files. To achieve this, I have enabled the configuration file to offer multiple graphic options (essentially encompassing most options available at ) ...

Saving a group of selected checkboxes as an array in Ionic: a step-by-step guide

I am working on a simple form with checkboxes and I need to send only the checked boxes to TypeScript. However, when I attempt to save the data by clicking the save button, I encounter an error message {test: undefined} Below is the form layout: <ion-c ...