3

Is there anyway you can do calculation in the style binding target in Angular4 ?

I've tried

[style.width]="{{1+1}}"

[style.width]="{{1+1}}px"

[style.width]="{{1px+1px}}"
ekclone
  • 1,030
  • 2
  • 17
  • 39

4 Answers4

5

You can use [style.width.px]="1 + 1" in order to achieve that.

QoP
  • 27,388
  • 16
  • 74
  • 74
  • Thanks, do you also perhaps know how to round a number in Angular4 bindings? – ekclone Jun 25 '17 at 04:59
  • there is a [built-in pipe](https://angular.io/api/common/DecimalPipe) for that, but maybe you'll need to create your own pipe like [this](https://stackoverflow.com/questions/41027749/angular-2-how-round-calculated-number) – QoP Jun 25 '17 at 05:06
1

this should work

   [style.width]="1+1+'px'"

Basically, when you're using [] , the must be expression and you should never put {{}} in the value, and this is a general Angular2 rule when you're using attribute binding.

[style.width]="{{1+1}}"   is wrong because of `{{}}` in the value
Milad
  • 27,506
  • 11
  • 76
  • 85
0
[style.height.px]="200"
[style.height.px]="200 + 50"
[style.height.px]="_commonService.screenHeight"
[style.height.px]="_commonService.screenHeight + 50"
[style.height.px]="_commonService.screenHeight - (isHomePage == true?80:140)"
/* Other Examples **/
[ngStyle]="{'margin-top': isHomePage == true ? '0px' : '60px' }" 
Shijith Mohanan
  • 743
  • 1
  • 7
  • 14
0

You should avoid doing style calculation inside your view. Simply create a function to handle this calculation and only return the result in view.

Danial Kalbasi
  • 434
  • 5
  • 9