关于angular:Angular4-样式绑定中的计算

Angular4 - Calculation in style bindings

无论如何,您是否可以在Angular 4的样式绑定目标中进行计算?

我已经尝试过

1
2
3
4
5
[style.width]="{{1+1}}"

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

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

您可以使用[style.width.px]="1 + 1"来实现。


这应该可以工作

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

基本上,当您使用[]时,必须为表达式,并且切勿在值中放入{{}},这是使用属性绑定时的Angular2通用规则。

1
[style.width]="{{1+1}}"   is wrong because of `{{}}` in the value

您应该避免在视图内部进行样式计算。只需创建一个函数来处理此计算,然后仅在视图中返回结果即可。


1
2
3
4
5
6
7
[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' }"