Search code examples
angularng-style

How can I apply styles dynamically with ngStyle?


How can i switch left px value with right based on a boolean ?

I want to switch [ngStyle]="{ 'left.px': offSetX } with [ngStyle]="{ 'right.px': offSetX } based on a condition

    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

Edit: I want to replace the style as in Remove the left if I apply right, and Remove Right when left is applied because left: 0px, right: 10px is not equal to right: 10px.

Solution: The correct way to reset left or right is to use initial instead of 0px


Solution

  • Why not keep them both and reset based on a condition ?

    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;
      }
    }