5

How can one bind the transform: translateX() style in Angular?

What I've tried:

<div [style.transform]="translateX({{x}})">

and

<div [style.transform.translateX.px]="x">
ᅙᄉᅙ
  • 17,132
  • 10
  • 64
  • 97

3 Answers3

9

This should work

<div [style.transform]="'translateX(' + x + 'px)'">

Edit

It seems that it is necessary to bypass XSS protection for this to work.

QoP
  • 24,748
  • 16
  • 67
  • 72
0
[ngStyle]="{'transform': 'translateX(' + transX + 'px)'}"

where transX is a component variable.

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
SoEzPz
  • 13,409
  • 8
  • 60
  • 61
0

The accepted answer works but you can make you code a lot cleaner by using methods as the binding of your style properties

<div *ngFor="let il of imageLayers">
    <img class="divFloatLayer" 
        [src]="il.img_src" 
        [style.left]="il.getLeftPx()"
        [style.top]="il.getTopPx()"
        [style.z-index]="il.getZindex()"
        [style.transform]="il.getTransform()"
    />
</div>

In the class that contains the values that you need to bind to:

getLeftPx() {
    return `${this.left}px` ;
}

getTopPx() {
    return `${this.top}px` ;
}

getZindex() {
    return `${this.z_index}` ;
}

getTransform() {
    return `translateX(${this.x}px)`;
}