Angular-如何应用[ngStyle]条件 [英] Angular - How to apply [ngStyle] conditions
问题描述
我有一个要根据条件设置样式的div.
I have a div that I want to style based on a condition.
如果styleOne为true,我希望背景颜色为红色.如果StyleTwo为true,则我希望背景颜色为蓝色.我已经用下面的代码完成了其中的一半.
If styleOne is true I want a background colour of red. If StyleTwo is true, I want the background colour to be blue. I've got half of it working with the below code.
<div id="myDiv" [ngStyle]="styleOne && {'background-color': 'red'}">
是否可以添加条件以说:
Is it possible to add a condition to say:
- 如果styleOne为true,请这样做
- 如果styleTwo是真实的,这样做吗?
修改
我认为我已经解决了.有用.不确定这是否是最好的方法:
I think i've resolved it. It works. Not sure if it's the best way:
<div id="div" [ngStyle]="styleOne && {'background-color': 'red'} || styleTwo && {'background-color': 'blue'}">
推荐答案
对于单个样式属性,可以使用以下语法:
For a single style attribute, you can use the following syntax:
<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">
我假设如果style1
或style2
都不是true
,则不应设置背景色.
I assumed that the background color should not be set if neither style1
nor style2
is true
.
由于问题标题提到了ngStyle
,因此以下是该指令的等效语法:
Since the question title mentions ngStyle
, here is the equivalent syntax with that directive:
<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">
这篇关于Angular-如何应用[ngStyle]条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!