【问题标题】:NgStyle doesn't apply with condition?NgStyle 不适用于条件?
【发布时间】:2020-10-09 03:39:24
【问题描述】:

谁能告诉我这是可行的

[style.height]="events?.length === 0 ? 'calc(100vh - 105px)' : null"

但这不是?

[ngStyle]="{'height: calc(100vh - 105px)': events?.length === 0 }"

还是这个?

[style.height]="{'calc(100vh - 105px)': events?.length === 0 }"

【问题讨论】:

  • 语法错误。试试[ngStyle]="{'height' : events?.length === 0 ? 'calc(100vh - 105px)' : null }"

标签: html css angular ng-style


【解决方案1】:

ngStyle 上,您需要将值作为json 数据的样式属性。在该json 数据上,键应为style 名称,值应为css 属性值,如下所示。

[ngStyle] = "{ 'height': events?.length === 0 ? 'calc(100vh - 105px)' : null }"

但是在你的代码上,

[ngStyle]="{'height: calc(100vh - 105px)': events?.length === 0 }"

您已将完整的 [style name]: [style value] 作为密钥放在 json 数据上,它不适用于 ngStyle

[style.height] 表示height html 属性上的height css 属性。 所以[style.height]="'100px'"style="height: 100px;"意思一样。

在这段代码中,

[style.height]="{'calc(100vh - 105px)': events?.length === 0 }"

您已将json 对象放入style.height,这是不可接受的height css 属性值,因此它不起作用。

【讨论】:

  • 我正在尝试找到一个更简单的解决方案(没有三元运算符)尝试其他示例但没有任何运气。没有三元有什么办法吗?
  • 您可以使用 [ngClass] 代替。创建一个名为“.abc { height: calc(100vh - 105px); } 的类并使用如下。[ngClass]="{ 'abc': events.length === 0 }"
  • 我已经有一个像这样的 ngClass [ngClass]="StyleLeftCol" 有一些变量
  • 或者您可以在控制器上创建名为additionalStyles 的变量,并根据事件向该值添加其他样式。并且可以在模板上设置[style]="additionalStyles"。 @user1186050
  • 我创建了这个,我认为它对我来说可能是最好的。 [ngClass]="{ StyleLeftCol: true, 'full-height': events?.length === 0}"
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 2018-01-30
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 2021-01-16
相关资源
最近更新 更多