【问题标题】:How to apply transform scale inline style in Angular?如何在 Angular 中应用变换比例内联样式?
【发布时间】:2020-03-22 03:39:21
【问题描述】:

如何通过从角度传递值来应用变换内联样式

这里是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;
}

【问题讨论】:

    标签: angular ng-style


    【解决方案1】:

    我会这样做:

    .ts 文件

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

    模板

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

    .7 和 .5 将来自您的动态变量等。

    blitz 已更新。

    如果您不希望它与 X 和 Y 上的刻度如此捆绑,您可以通过发送一个完整的 transform 字符串来做得更优雅,该字符串是通过使用您的类属性/输入/生成的您需要的变量。 HTML 看起来更像:

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

    【讨论】:

      【解决方案2】:

      您可以使用ngStyle 指令来实现此目的。我在AppComponent 中添加了一些缩放值的输入元素,并将它们传递给HelloComponent,其中缩放值用于创建变换样式。

      https://stackblitz.com/edit/angular-acskvs

      【讨论】:

      • 我还将 changeDetection 设置为 OnPush,这样每次 Angular 在 HelloComponent 中运行其更改检测时就不会调用 getter。否则,如果您将日志放入 getter 中,您会看到它被多次调用,这可能会导致性能问题。
      【解决方案3】:
      const element = document.getElementById(id) as HTMLElement;
      // set style
      element.style.transform = 'scaleY(1)';
      // remove style
      element.style.transform = '';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-26
        • 1970-01-01
        • 2018-07-01
        • 1970-01-01
        • 2021-06-02
        • 1970-01-01
        • 2017-03-13
        相关资源
        最近更新 更多