0
votes

I'm having an issue with styles not being applied to elements. If I add style information to the component's styles parameter, or provide a CSS file in the styleUrls parameter, I get the expected results. However, inline HTML styles are not being applied. In the below example I'm trying to apply a red background to a div, but it stays white. This HTML exists as a template for an Angular Component.

<div style="background: red;">test</div>

However, if I add ngStyle="" to the element such as:

<div style="background: red;" ngStyle="">test</div>

Then Angular renders the background of the div in red.

Any ideas what is causing Angular to ignore style attributes like this?

2

2 Answers

1
votes

ngStyle and style are the same, they apply styles You can have both populated, and both will apply styles (One will not cancel out the other unless both are trying to do the same thing), but with [ngStyle] you can bind it to attributes in your code, like this: [ngStyle]="{backgroundColor: getColor()}", getColor() being a function that retards a string or hex for a color.

This snippet for example should be valid in angular 2 (At work so cant verify)

<div style="background-color: black;" [ngStyle]="{color: white}">text with back background and white font color</div>

Why the ngStyle directive is declared into the []?

0
votes

I ended up upgrading all of my libraries (from Angular 4 to Angular 5) and with no code changes the style information was rendered as expected.