Angular: A guide to dynamically applying colors to elements with user input and storing them in a database

I am currently implementing a method to apply CSS colors and styles obtained from an API endpoint to HTML elements.

Although I have achieved this functionality, I believe there may be room for improvement in terms of best practices.

This is the current implementation. Do you have any suggestions on how to accomplish this in a more professional manner?

Here is my .ts file:

getColors(){
    this.api.get("http://127.0.0.1:8000/colors").subscribe((res:any)=>{
      this.colors = res.color
      console.log(res)
      document.documentElement.style.setProperty("--primary", this.colors)
    })
  }

and .html file:

<header class="header">
    <div class="headerdiv">
        <h1>Welcome to Overflow</h1>
    </div>
</header>

<style>
    .header{
        background-color: var(--primary);
    }
    h3, h1{
        color: var(--textcolor);
    }
</style>

Answer №1

Avoid injecting CSS or any code through endpoints.

Injecting CSS can lead to problems and make your application vulnerable to code injection.

For more information on the risks of CSS injection, check out this article.

I recommend reevaluating your approach and loading colors from within the application. Consider retrieving an ID from the API that corresponds to a color, allowing you to manage colors externally without the risk of malicious injections.

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

Encountering an error message stating "Unable to recognize property 'screen' of undefined" when incorporating Quasar components into a Storybook story

I seem to be encountering an issue when trying to render Quasar components in Storybook using Vue and Quasar. I have a suspicion that the story is not recognizing the Quasar tags. I followed the steps to set up the project from and then initiated npx sb i ...

`Unveil the hidden edges of the Google timeline chart`

Does anyone know how to remove the chart border from a Google timeline chart using this script? <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load ...

Grid Column with Checkboxes in Kendo UI for Vue

Seeking help in adding a checkbox column to a Kendo UI Vue grid. The column should display the values of a boolean field from the grid's data source. While I am aware of how to add a checkbox column for selection as demonstrated here: https://www.tele ...

Angular2 Error: ngClass used in a Host component, "is not recognized as a valid native property"

Is it feasible to utilize the "ngClass" directive within the host for a component or directive? @Component({ selector: 'custom', template: `<div [ngClass]="classMap"></div> // It works <ng-content></ng-content&g ...

I offer a unique service that creates custom toolbars with a variety of classes to choose from

menu component import { QueryParam } from "./query-param"; import { QueryRouterLink } from "./query-router-link"; export class Menu { link: string; name: string; queryParam: QueryParam[]; queryRouterLink?: QueryRouterLink; } QueryParam class e ...

Encountering an issue with usememo in React js?

I'm currently experimenting with the useMemo hook in React JS. The goal is to sort an array of strings within a function. However, when I return the array from the function, only the first element is being returned. Can someone please assist me in ide ...

Angular showcases the presence of a signed-in user at page load, disregarding the absence of

Currently, I am following a course where I have implemented a simple login form inside the navigation bar: <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-primary"> <div class="container"> ...

Utilizing THREE.js to animate a skinned mesh along a curved path

I am working with a skinned mesh of a 'snake' that I exported from Blender. This snake has bones resembling a spine that I want to animate along a curve called SplineCurve3. While I can calculate points along the spline and the angles between th ...

struggling to locate name using typescript and deno

Here is the snippet of code I'm working with: /** * map.ts */ // @deno-types="./libs/@types/geojson/index.d.ts" // @deno-types="./libs/@types/mapbox-gl/index.d.ts" mapboxgl.accessToken = "toto"; var map = new mapbo ...

The timestamp is currently displaying as 2014-11-02T05:00:00.000Z rather than the expected 2014-11-02 00:00:00

Issue: The SELECT * query is returning dates in the wrong format. I am using the mysql2 module to run connection.query() and pass data to a server-side variable, then accessing it on the client-side with AJAX. router.post('/applicants', functi ...

Incorporating icons into an Angular library: What you need to know

Looking to seamlessly integrate SVG icons into the template of my Angular library, I have a few inquiries: Where is the ideal location for the /assets folder? Should it be situated under /src or /src/lib in the library's structure? What specific chan ...

GraphQL/Relay Schema "Field cannot be queried..."

I'm encountering an issue when trying to query specific fields in graphql/relay. My goal is to retrieve the "courseName" field for Courses from the schema provided below. For instance, if I query the User with: { user(id:1){firstname,lastname}} T ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

Error: The architecture arm64 has duplicate symbols in React-Native

I am encountering an issue in my React-Native project after installing vision-camera-code-scanner. When attempting to build the project in XCode, I am faced with the following error message: duplicate symbol '_OBJC_CLASS_$_GDTCCTCompressionHelper&apos ...

Resolving label overlapping issue in Chart.js version 2

I am currently utilizing Chart.js 2 for a project of mine. I've successfully customized the style, but there's one persistent issue that I can't seem to resolve and it's becoming quite frustrating. Occasionally, the last label on the x ...

Having trouble getting my AngularJS directive with a number in the name to function properly

Check out my code snippet: app.directive('3dPlansSlider', function(){ return { controller: 'projectCtrl', restrict: 'E', templateUrl: 'views/3dPlansSlider.html', link: function(scope, element, attr ...

Implementing a JQuery click method within a class structure

I'm having trouble getting the functionality of the .click function to work on my page unless I paste it into the browser console. In my class, this is what I have: var myClass = function(){ var toggleChecked = function(){ $('#myCheck ...

Produces consistent results despite variations in tag names within the DOM

While iterating over each element (post) in an array, I have assigned each HTML tag name a value of post._id. In the DOM, the outputs have different values as expected. However, when I try to capture these values in the React Profile component, the console ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

What could be causing the success of the initial Angular 9 Put request on the MVC Core 2.2 API Controller to be followed by failures on subsequent PUT requests resulting in http error 302 and/or 503?

My journey with ASP.NET Core, Angular HttpClient, and Observables has been a learning curve. A year ago, I had questions, but as time passed, these queries no longer seemed necessary. The key lesson I learned was about utilizing the [Authorize] attribute ...