这是我的 html 的一部分:
<div class="container">
这是相关的 CSS 部分:
.container{
width:100%;
height: 45px;}
@media (min-width: 768px) {
.container{
height:60px;}
现在我想通过 ngStyle 将这个 div 的样式绑定(bind)到一个属性上。我在 app.component.ts 中有一个名为 isShrinked
的属性,当 isShrinked===true
时,我希望 div 的高度为 10px,否则高度将是 container
类的 css 样式设置的默认值。
现在我阅读了有关 ngStyle 的 Angular 文档但我找不到正确的语法来实现这一点。我能做的最接近的是添加类似[ngStyle]="{'height': isShrinked?'10px':''}"
的内容,但这显然行不通,因为我必须给出一个在此三元表达式中将值移到右侧,这不是我打算做的。
有人可以帮帮我吗?
最佳答案
以下语法应该有效:
[ngStyle]="isShrinked ? { 'height': '10px' } : {}"
[ngStyle]="isShrinked ? { 'height': '10px' } : null"
如果只设置一个样式属性,用这个特定的样式绑定(bind)可以获得相同的结果:
[style.height.px]="isShrinked ? 10 : null"
参见 this stackblitz用于演示。
关于javascript - 如何在 Angular 中将 ngStyle 设置为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51256353/