Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 [style.margin-top]

Tags:

angular

I need to get height of img and then change margin-top subtract from it height of img. I tried this code below but unfortunately this didn't work

<img [style.marginTop.px]="marginTop - '[style.height.px]' "class="noteImg">

How elegant resolve this question ? I will be glad any your suggestions.

Full code

<div class="container-fluid noteContainer" *ngFor="let data of dataPost; let i = index">
    <div class="noteWrapperImg">
        <img [style.marginTop.px]="HOW TO DO IT?" src="{{data?.image}}" class="noteImg" alt="{{data?.altImage}}">
        <a class="{{i%2 == 1 ? 'notePDataNotEven': 'notePDataEven'}}" [class.css]="i%2 == 1">
           <i class="ion-ios-clock-outline"></i> {{data?.data}}
        </a>
    </div>
</div>
like image 306
Lestoroer Avatar asked Nov 12 '16 21:11

Lestoroer


2 Answers

The proper node's style margin-top property is marginTop, but you cannot do it like this. You should access style in your component and retrieve height property first yo use it in your template.

As you use an *ngFor loop, you can do it by adding a template variable to image and passing it to some method that returns its height. Like this:

<div *ngFor="let data of dataPost>
    <img #img [style.marginTop.px]="getImgMarginTop(img)" src="http://image-src.png">
</div>

Then add to your component a method that returns your image height.

  getImgMarginTop(img) {
    return img.style.marginTop - img.clientHeight
  }
like image 183
Yaroslav Grishajev Avatar answered Oct 18 '22 03:10

Yaroslav Grishajev


As far as I know, you cannot get value from using directive [style.height.px], your best option is using direct access to the DOM using ElementRef and then access its height property, and used it in your calculation

like image 42
Michael Avatar answered Oct 18 '22 04:10

Michael