NGStyle Changes Not Always Reflected

706 Views Asked by At

I have an element that takes ng style but the styles aren't always being applied as expected when the style object changes. I'm specifically refering to the css animation below but I've seen similar behavior with background.

<div [ngStyle]="_innerStyle">
export class WidgetContainerComponent implements OnInit {
  _innerStyle?: {
    [klass: string]: any;
  } | null;
...
}

For example _innerStyle is

animation: "flash"
animation-duration: "1s"
animation-iteration-count: "infinite"
background-color: "#ffffff"
box-shadow: "0px 2px 1px -1px rgba(0,0,0,.2), 0px 1px 1px 0px rgba(0,0,0,.14), 0px 1px 3px 0px rgba(0,0,0,.12)"
color: "#199719"

Result in DOM:

animation: 1s ease 0s infinite normal none running flash;

and changes to

animation: "rubberBand"
animation-duration: "1s"
animation-iteration-count: "infinite"
background-color: "#b53b3b"
box-shadow: "0px 2px 1px -1px rgba(0,0,0,.2), 0px 1px 1px 0px rgba(0,0,0,.14), 0px 1px 3px 0px rgba(0,0,0,.12)"
color: "#199719"

Result in DOM:

0s ease 0s infinite normal none running flash

Why is animation-duration being set to 0s suddenly? I'm printing the JSON object and it does not have 0s it has 1s.

Even weirder, if the animation-duration's are different values they get applied correctly on change?! For example: 1s to 2s instead of 1s to 1s

I expect the dom style to reflect the style object exactly. Am I doing something wrong?! Is there a way to debug ngStyles behavior?

2

There are 2 best solutions below

0
On BEST ANSWER

I come to realize animation is a shorthand property.
I really wanted to use animation-name.

If I were to use animation as the css property I would need to build the shorthand value.

By using the individual animation properties the animation is applied correctly and not overwritten by animation shorthand property.

1
On

I think this could be related to change detection where Angular is not kicking in change detection because the reference (location in memory) of _innerStyle does not change.

Every time _innerStyle changes in your TypeScript/JavaScript, try updating it immutably like so:

this._innerStyle = {
   ...this._innerStyle, // keep all of the old properties (spread operator)
  color: 'red',         // change the properties here though
  'background-color': red,
};