I am having issues dynamically updating an elements style.
I am overlaying some margins on top of an image. I created a child component to handle this. I call a function on my child component which calculates the margins and then sets a variable.
Here is the parent component call, which is triggered by a button click.
showMargins() {
if (this.showingMargins) {
this.showingMargins = false;
} else {
this.showingMargins = true;
this.marginComponent.calculateMargins();
}
}
And here is my child component:
marginStyles: any = {};
...
calculateMargins() {
//logic
...
//set the property
this.marginStyles = {
'height.px': height,
'margin-left.px': left
}
}
And then in my template
<div id="margin-left" [ngStyle]="marginStyles">
I've tried using a function as well
private leftDiv() {
debugger;
return this.marginStyles;
}
thus changing my template to
<div id="margin-left" [ngStyle]="leftDiv()">
but to no avail. If I hardcode the values when I declare the variable it works fine.
marginStyles: any = {'height.px': 200, 'margin-left.px': 20};
And if I hardcode it in the template it works fine as well; it's just failing after I've done my calculations and won't render the lines that I'm overlaying. Where have I gone wrong? If it helps, I'm on Angular 4.
Edit: I moved all of my logic to my parent component, and everything looks fine. It appears to me that the values I am for marginStyle are not being updated in the child component, which is baffling to me. They should be updating. ngStyle is working fine, it's the variable that is not being updated.
calculateMargins()is called?<div>{{ marginStyles | json }}</div>. It may not be in a valid state (heightandleftmay not be valid numbers in your code).