0

I'm trying to dynamically create some HTML based on query results from my database. As a result, I'm not able to have the HTML ready in the Angular template to bind attributes to. The HTML is added via [innerHTML] using data from a string in the database. Given Angular's AOT compiling method, the string in the database cannot include an attribute to bind to.

This following is my attempt at resolving this particular request.

I would like to set the following attribute, whereby once the innerHTML has rendered, I can find the 'header' element by the ID and add an attribute that displays a top border based on a variable in the component.ts file.

However, I keep receiving the following error:

Failed to execute 'setAttribute' on 'Element': '[style.border-top-color]' is not a valid attribute name.

myChosenColour = "#007cbe"

...

document.getElementById('header').setAttribute('[style.border-top-color]', this.myChosenColour)

It's worth noting: I need the square brackets to bind to the local variable, as there will be inputs on screen where new values can be entered, and therefore the colour will be changed and will need to update dynamically.

Que
  • 957
  • 2
  • 14
  • 35
  • Setting the attribute with square brackets like that won't work unless you recompile the component again after setting it. Why not just use `document.getElementById('header').style.borderTopColor = this.myChosenColor;`? – Heretic Monkey Feb 06 '19 at 15:29
  • Thanks Heretic. Just setting the style attribute works, but as mentioned at the end of my post, there's an input on screen that'll allow users to enter a hex value to change the colour. By just setting the style attribute with no form of binding, means that the colour can't change on the fly. – Que Feb 06 '19 at 15:34
  • One thing you can do: implement `myChosenColour` as a getter/setter property. You can then update the element style attribute in the property setter. – ConnorsFan Feb 06 '19 at 15:37
  • Hey ConnorsFan, not really sure how to do that. Do you have an example? – Que Feb 06 '19 at 16:40
  • ConnorsFan has a good ideea. [Here is an example of how to do what he tell in C#.](https://stackoverflow.com/questions/11159438/looking-for-a-short-simple-example-of-getters-setters-in-c-sharp) – Dragos matianu Feb 06 '19 at 18:00

0 Answers0