如何使用 ngStyle 动态应用样式?

How can I apply styles dynamically with ngStyle?

如何根据布尔值切换左像素值和右像素值?

我想根据条件 [ngStyle]="{ 'left.px': offSetX }[ngStyle]="{ 'right.px': offSetX } 切换

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

@Component({
  selector: "hello",
  template: `
    <div class="myDiv" [ngStyle]="{ 'left.px': offSetX }"></div>

    <button (click)="applyRightStyle()">Apply Right Style</button>
  `,
  styles: [
    `
      .myDiv {
        border: 1px solid black;
        height: 200px;
        width: 200px;
        position: absolute;
        top: 100px;
        margin-left: 50px;
      }
    `
  ]
})
export class HelloComponent {
  @Input() name: string;

  offSetX = 100;
  applyRightBoolean = false;

  applyRightStyle() {}
}

Stackblitz Demo

编辑:我想替换样式,如应用右侧时删除左侧,应用左侧时删除右侧,因为 left: 0px, right: 10px 不等于 right: 10px

解决方法:重置leftright的正确方法是使用initial而不是0px

为什么不同时保留它们并根据条件重置?

Stackblitz

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

@Component({
  selector: "hello",
  template: `
    <div class="myDiv" [ngStyle]="{ 'left.px': !applyRightBoolean ? offSetX : 0, 'right.px': applyRightBoolean ? offSetX : 0 }"></div>

    <button (click)="applyRightStyle()">Apply Right Style</button>
  `,
  styles: [
    `
      .myDiv {
        border: 1px solid black;
        height: 200px;
        width: 200px;
        position: absolute;
        top: 100px;
        margin-left: 50px;
      }
    `
  ]
})
export class HelloComponent {
  @Input() name: string;

  offSetX = 100;
  applyRightBoolean = false;

  applyRightStyle() {
    this.applyRightBoolean = true;
  }
}
public bgcolor = "red";

 [style.backgroundColor]="bgcolor"
second way used like that for multiple

public bgcolor = {
    backgroundColor:"orange"
};

[ngStyle]="bgcolor"

适合你这样使用的风格

[ngStyle]="{ backgroundColor:'#' + element.color }"

<ng-container matColumnDef="color">
  <th mat-header-cell *matHeaderCellDef mat-sort-header> color </th>
  <td mat-cell *matCellDef="let element" [ngStyle]="{ backgroundColor:'#' + element.color }" > #{{element.color}} </td>
</ng-container>

我认为我们必须同时管理这两种风格。它也适用于 ngStyle 但我喜欢 [style.xxx] 语法:

@Component({
  selector: "hello",
  template: `
    <div class="myDiv" [style.left.px]="offSetLeft" [style.right.px]="offSetRight"></div>

    <button (click)="applyRightStyle()">Apply Right Style</button>
    <button (click)="applyLeftStyle()">Apply Left Style</button>

  `
})
export class HelloComponent {
  @Input() name: string;

  offSetLeft = 100;
  offSetRight = 0;
  applyRightBoolean = false;

  applyRightStyle() {
    this.offSetLeft = 0;
    this.offSetRight = 50;
  }

  applyLeftStyle() {
    this.offSetLeft = 100;
    this.offSetRight = 0;
  }
}

分叉了你的stackblitz

更新:

[ngStyle]="{ condition ? '\'left.px\': offSetX' : '\'right.px\': offSetX'}