CAUTION: cleaning unsecure style value background-color

Incorporating Angular, I am retrieving data from Firebase to enable user chat messages to display in a color chosen by the user, specifically using item.color. However, encountering an issue where for a user who selects blue as their color, a warning message appears:

WARNING: sanitizing unsafe style value background-color:blue (see http://g.co/ng/security#xss).

Here is the code snippet for my HTML:

<div *ngFor="let item of items; let i = index">
  <ion-card style="background-color:{{item.color}}" [ngClass]="{'me': item.sender == sender, 'notme': item.sender != sender}">
    <ion-card-header *ngIf="item.sender != sender">
      @{{item.sender}}
    </ion-card-header>
    <ion-card-content>
      {{item.message}}
    </ion-card-content>
  </ion-card>
</div>

Additionally, here is a snippet from my TypeScript:

import { Component, OnInit, ViewChild } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'page-chat',
  templateUrl: 'chat.html'
})
export class ChatPage{

  @ViewChild(Content) content: Content;

  user: {};
  style;

  ionViewDidLoad(){
    firebase.auth().onAuthStateChanged((user)=> {
      this.user = user;
      console.log('authState',user);
      if (user) {
        var uid = user.uid;
        firebase.database().ref('/userprofile/' + uid + '/' + 'chatcolor').once('value').then((snapshot)=> {
          this.color = (snapshot.val());
        });
      }
    });
  }


  constructor(public af: AngularFireDatabase, private Svc: Service, private sanitizer: DomSanitizer) {
    this.style = sanitizer.bypassSecurityTrustStyle("blue")
  }

}

How can I resolve this issue and successfully implement user-selected chat message colors?

Answer №1

Recently faced a similar issue and was able to resolve it using the following code snippet (Special thanks to Sape The Mape):

[ngStyle]="{'background-color': item.color}"

For those looking to explore further, I came across a helpful article on dynamic styles in Angular: dynamic styles as well as the official documentation on binding style

Hoping this information proves useful to you as well :)

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

Customizing font color upon hover in Next.js and Tailwind.css

Recently, I developed a Navbar component that displays a purple link when navigating to pages like Home or Projects. The issue arises when the background color is light; in this case, the link turns green on hover instead of staying purple. How would I adj ...

Why isn't my Promise fulfilling its purpose?

Having trouble with promises, I believe I grasp the concept but it's not functioning as expected in my project. Here is a snippet of my code : (I am working with TypeScript using Angular 2 and Ionic 2) ngOnInit() { Promise.resolve(this.loadStatut ...

Collaborate on code for a cross-platform mobile application and a traditional desktop web application

I have a vision to create a cutting-edge app that can be utilized as both a hybrid mobile application and a desktop web application. For the most part, the logic and user interface will remain consistent across both versions. However, there are a few key ...

Implementing Angular - Injecting a component dynamically into another component

Currently, I am working on developing a small UI components framework for my personal use and enjoyment. One of the components I'm working on is a Tab component. To test this component, I need to dynamically inject another component (TabContainerCompo ...

Angular and Bootstrap are like peanut butter and jelly -

Recently, I've been delving into Angular and attempting to integrate Bootstrap into my projects. To install Bootstrap using npm, I ran the following command: cmd npm install bootstrap --save After the installation, I imported the necessary styles in ...

Ways to implement a loading template with OnPush change detection technique

Currently, I am retrieving a route parameter: searchResults$: Observable<string[]>; constructor( private route: ActivatedRoute, private svc: SearchService) { this.searchResults$ = this.route.paramMap.pipe( map((p: ParamMap) => p.get(&a ...

Unable to include option object in the SHA3 function using typescript

The SHA3 function allows for customizing the output length, as demonstrated in the code snippet below: var hash = CryptoJS.SHA3("Message", { outputLength: 512 }); var hash = CryptoJS.SHA3("Message", { outputLength: 384 }); var hash = CryptoJS.SHA3("Messag ...

Issue encountered with dynamic ngStyle variable: ERROR Error: Unable to locate a supporting object 'ngStyleSmall'

I have defined two variables for ngstyle ngStyleSmall = { width: '150px !important', 'max-width': '150px', }; ngStylemedium = { width: '250px !important', 'max-width&apo ...

There is no mistake when using a value that falls outside of a TypeScript

Expecting to encounter a compile time error with this code, but it seems my understanding of enums is off... enum SortDirection { ascending = 1, descending = -1 } type IndexSpec = {[index: string]: SortDirection}; var i: IndexSpec = {thing: 3}; ...

Anticipate the absence of a specific object length

I have an Object that I need to test for null: getLastTeamUpdatedItemLogBuffer(): IBufferElement { const storageItems = this.storageSvc.getItem(StorageKey.lastTeamUpdatedItem, true) as IBufferElement; return storageItems || null; } This is the IBufferE ...

Transforming a JavaScript component based on classes into a TypeScript component by employing dynamic prop destructuring

My current setup involves a class based component that looks like this class ArInput extends React.Component { render() { const { shadowless, success, error } = this.props; const inputStyles = [ styles.input, !shadowless && s ...

Guide to defining font style in vanilla-extract/CSS

I'm trying to import a fontFace using vanilla-extract/css but I'm having trouble figuring out how to do it. The code provided in the documentation is as follows: import { fontFace, style } from '@vanilla-extract/css'; const myFont = fo ...

tips on rotating an image using nativescript

I'm attempting to insert a picture from my device and then adjust its orientation in nativescript. So far, I've been using imageSource to import the picture, but I'm unsure how to rotate it. If anyone has suggestions for another class that c ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Comparing the functions of useMemo and the combination of useEffect with useState

Is there a benefit in utilizing the useMemo hook instead of using a combination of useEffect and useState for a complex function call? Here are two custom hooks that seem to function similarly, with the only difference being that useMemo initially returns ...

NextJS function utilizes its own references within React and automatically fetches data without the need for an import

I recently purchased this template and I'm trying to figure out which page the code snippet "{getLayout(<Component {...pageProps} />)}" is directed to during the initial load. It seems like it might be a global variable hidden somewher ...

Filtering an array with radio buttons in Angular

I am working with a JSON list that contains various audio files categorized by genre, along with their corresponding URLs. export const musicList = [ { 'id': 0, 'catName': 'upload', 'audios': [ { ...

Struggling to implement JSS hover functionality in a project using React, Typescript, and Material UI

I am a newcomer to the world of React/Typescript/Material UI and I am trying to understand how to work with these technologies together. While researching, I came across a similar question related to using hover with Material-UI. However, the syntax was d ...

React/Typescript - Managing various event types within a unified onChange function

In my current project, I am working with a form that includes various types of input fields using the mui library. My goal is to gather the values from these diverse input components and store them in a single state within a Grandparent component. While I ...

A guide on incorporating jQuery alert messages into Angular 2

Whenever I submit a form by clicking on the "send message" button, I want to display an Alert message using jQuery. However, currently, I have to double click for the alert message to appear. How can I make it so that the alert message is shown with just o ...