angularng-style

How to apply transform scale inline style in Angular?


How Can I apply transform inline style by passing values from angular

Here is the Stackblitz Link

import { Component, Input } from "@angular/core";

@Component({
  selector: "hello",
  template: `
    <h1>Hello {{ name }}!</h1>

    <div>Normal</div>
    <div class="scaled">Scaled</div>

    <div
      class="scaledng"
      [style.transform.scale.x]="scaleX"
      [style.transform.scale.y]="scaleY"
    >
      Scaled by Angular
    </div>

    <p>
      How can I scale the last div by passing angular variables
    </p>
  `,
  styles: [
    `
      div {
        width: 80px;
        height: 80px;
        background-color: skyblue;
      }

      .scaled {
        transform: scale(0.7, 0.5); /* Equal to scaleX(0.7) scaleY(0.7) */
        background-color: pink;
      }

      .scaledng {
        background-color: pink;
      }
    `
  ]
})
export class HelloComponent {
  @Input() name: string;

  scaleX = 0.7;
  scaleY = 0.5;
}

Solution

  • I would do it this way:

    .ts file

    scaleXY = 'scale(' + .7 + ',' + .5 + ')';
    

    template

    <div class="scaledng" [style.transform]="scaleXY">Scaled by Angular</div>
    

    .7 and .5 would come from your dynamic variables, etc.

    blitz updated.

    And if you don't want it to be so tied up with the scale on both X and Y, you could do it more elegant by sending a full transform string, generated by playing with your class properties/inputs/variables as you would need. The HTML would look more like:

    <div class="scaledng" [style.transform]="transformStyle">Scaled by Angular</div>