Search code examples
cssangularstylesexpression

In Angular, can I add css style together with double curly brackets?


I am trying to create a style for my element using a variable name, which is a number, and adding % at the end. I am currently doing it inline like this:

<progress-bar
  style="{{batteryLifeLeft+'%'}}"
/>

What is wrong with it? Can you not add things together in this expression? I am getting the error: "Property value expected" and "at-rule or selector expected."


Solution

  • Correct syntax would be [ngStyle]="{'width.%': batteryLifeLeft}". https://angular.io/api/common/NgStyle

    <div style="width: {{ batteryLifeLeft }}%">
      {{ batteryLifeLeft }}% this wont work
    </div>
    <br />
    <div [ngStyle]="{ 'width.%': batteryLifeLeft }">
      {{ batteryLifeLeft }}% this will work
    </div>
    
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      batteryLifeLeft = 50;
      constructor() {}
    }
    

    Working example is on StackBlitz