Reputation: 81
I'm trying to get the exact pixel value of a margin-left style applied to a div element with the calc() function, I need this value sent to a function in my typescript, so far my code for this looks as follows
HTML:
<div id="cont" class="container" [style.width.px]="getWidth()"
[ngStyle]="getOffset([style.margin-left])">
TypeScript:
getOffset(marg){
var style;
if(marg > 130){
style = {'margin-left': 'calc(50% -'+String(this.offsets[this.arrPosWidth])+'px)' };
}else{
style = {'margin-left': '130px' };
}
return style
}
Sending the style through that function was a long shot and I've tried accessing the margin-left style with element.style but this just returns a literal string with calc(50%-..px). Is there any way for me to get the value in pixels for the margin-left style applied to that particular element?
Upvotes: 2
Views: 1490
Reputation: 18805
You can achieve this through the ngAfterContentInit
Lifecycle hook.
Here is a working example: https://stackblitz.com/edit/angular-dbfp8x
export class AppComponent implements AfterViewInit {
// this is what we initially set the margin to
public margin:number = 75;
// Bound to your element
@ViewChild('myElem') element: ElementRef;
ngAfterViewInit(){
// get the current margin and then strip off the 'px'
let currentMargin:number = parseInt((this.element.nativeElement.style.marginLeft as string).substring(0,2));
// add any restriction logic you need.
if(currentMargin > 25){
this.margin = 25;
}
}
}
Upvotes: 1