2

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?

2
  • You want to calculate the new left margin based on the current left margin? That will probably cause an infinite loop. Commented Feb 16, 2019 at 23:28
  • I just want to prevent the margin-left of that element going below 130px. Commented Feb 16, 2019 at 23:54

1 Answer 1

1

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;
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.