I'm feeling a little puzzled about why the ngStyle
directive is not behaving as anticipated. I came across this issue while following a tutorial by Brad Traversy on Udemy, where we were instructed to utilize ngStyle
in the following manner:
<h3 [ngStyle]="currentStyles" >{{user.firstName}} {{user.lastName}}</h3>
This code snippet relies on the currentStyles
property defined in the component class, like so:
currentStyles = {'padding-top': this.showExtended ? '15px': '0'}
The showExtended
property is a boolean that is toggled using a method:
toggleExtended() {
this.showExtended = !this.showExtended;
}
Expected behavior: the padding-top
of the h3 element should transition from 0 to 15px when showExtended
is switched from false
to true
. The showExtended
property is indeed changing, and other parts of the component relying on it are working correctly. However, it seems that the ngStyle
directive only evaluates once during the initial render and does not update when the component property changes.
To resolve this issue, I discovered a workaround by creating a method that returned a locally scoped variable:
getCurrentStyles() {
let styles = {
'padding-top': this.showExtended ? '0' : '40px'
}
return styles;
}
and then updating the element to:
<h3 [ngStyle]="getCurrentStyles()">{{user.firstName}} {{user.lastName}}</h3>
This workaround indeed produced the expected results. In summary, the ternary condition within the currentStyles
object only gets evaluated during the component's initial mount, and the value does not update when the property changes.
What could I be overlooking in this scenario?