Reputation: 351
I'm a little confused why ngStyle
is not working as expected. I'm following a tutorial by Brad Traversy on Udemy, and we're instructed to use ngStyle
like so:
<h3 [ngStyle]="currentStyles" >{{user.firstName}} {{user.lastName}}</h3>
Which would rely on the currentStyles
property set on the component class, as follows:
currentStyles = {'padding-top': this.showExtended ? '15px': '0'}
the showExtended
property is a boolean, which is toggled by a method:
toggleExtended() {
this.showExtended = !this.showExtended;
}
Expected behavior: the padding-top
on the h3 element should change from 0 to 15px when this.showExtended is toggled from false
to true
. This property is indeed changing, as other parts of this component are reliant on it, and functioning as expected. However, It appears that ngStyle
is only evaluating on first render, and not updating when the property of the component changes.
The solution I found was to make a method that returned a function scoped variable:
getCurrentStyles() {
let styles = {
'padding-top': this.showExtended ? '0' : '40px'
}
return styles;
}
and set the element to
<h3 [ngStyle]="getCurrentStyles()">{{user.firstName}} {{user.lastName}}</h3>
This, in fact works as expected. To summarize: the ternary in that currentStyles object only evaluates on component mount, and that value then does not update when the value changes.
What am I missing here?
Upvotes: 0
Views: 1780
Reputation: 3319
Minor update to get what you want.
toggleExtended() {
this.showExtended = !this.showExtended;
this.currentStyles = { 'padding-top': this.showExtended ? '15px': '0' };
}
Angular evaluates change to currentStyles
object to trigger the redraw.
Upvotes: 1