Search code examples
cssangularng-style

How to use variable in [ngStyle] in angular?


I want to change position depends on some events. For example at the begining space from top should be 100px, but after button click should be 0px

<mat-list-item class="menu-item disabled " disableRipple (click)="toggleSubmenu($event)">
    <h3 matLine class="menu-item-text">Orchestration</h3>
  </mat-list-item>

I want to code some similar to

<mat-list-item class="menu-item disabled " disableRipple (click)="toggleSubmenu($event)" [ngStyle]={top: myVarilable+'px'}>
    <h3 matLine class="menu-item-text">Orchestration</h3>
  </mat-list-item>

but it doesnt work for me. Do you have some ideas to solve it?


Solution

  • I am not sure if is what you are looking for but you can pass an Object in the ngStyle, so you can use a function that returns a dynamically generated object.

    Something like that.

    HTML

    <p [ngStyle]="setMyStyles()">
      You say tomato, I say tomato
    </p>
    

    Component

    setMyStyles() {
      let styles = {
        'top': this.user.myVarilable + 'px',
      };
      return styles;
    }