Angular - How to apply [ngStyle] conditions

 ̄綄美尐妖づ 提交于 2019-12-20 17:31:03

问题


I have a div that I want to style based on a condition.

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:

  • if styleOne is true, do this
  • if styleTwo is true, do this?

Edit

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'}">

回答1:


For a single style attribute, you can use the following syntax:

<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">

I assumed that the background color should not be set if neither style1 nor style2 is true.


Since the question title mentions ngStyle, here is the equivalent syntax with that directive:

<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">



回答2:


You can use an inline if inside your ngStyle:

[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"

A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:

[style.background-color]="myColorVaraible"



回答3:


[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"


来源:https://stackoverflow.com/questions/49280975/angular-how-to-apply-ngstyle-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!