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">
P Varga
  • 19,174
  • 12
  • 70
  • 108

3 Answers3

10

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
  • 27,388
  • 16
  • 74
  • 74
0
[ngStyle]="{'transform': 'translateX(' + transX + 'px)'}"

where transX is a component variable.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
SoEzPz
  • 14,958
  • 8
  • 61
  • 64
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)`;
}
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99