I am trying to set CSS colors and styles that is fetched from an API endpoint to HTML elements.
I have been able to achieve this but I feel it is not the best practice.
This is what I have. Any suggestion to achieve this in a more professional way?
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(--h3color);
}
</style>
You should not inject CSS or any code via endpoint.
Loading CSS is problamtic. You are making you app very vunarable to code injection.
See Topics like CSS injection: what's the worst that can happen?
I suggest rethink you approach and load the color from inside the app. Like getting a id from the api which translates to a color. In that way you can control the color from outside without injection potential malicious code.