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

时间:2019-10-09 19:03:18

标签: angular ng-style

如何基于布尔值将px左值切换为右值?

我想根据条件用[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

4 个答案:

答案 0 :(得分:2)

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

Stackblitz

i <- 3
hist(Boston[, sectors[i]], ylab='Frequency', xlab=xlabels[i], main=titles[i])

答案 1 :(得分:2)

我认为我们必须同时管理两种样式。它也可以与[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; } } 语法:

C:\QGIS\apps\Python27\

分叉了您的stackblitz

答案 2 :(得分:0)

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>

答案 3 :(得分:0)

更新:

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