Angular - 如何应用[ngStyle]条件

134

我有一个div,我想根据条件进行样式设置。

如果styleOne为真,我想要背景颜色为红色。如果styleTwo为真,我想要背景颜色为蓝色。我已经使用以下代码完成了其中一半。

    <div id="myDiv" [ngStyle]="styleOne && {'background-color': 'red'}">

是否可以添加一个条件,说:

  • 如果styleOne为真,则执行此操作
  • 如果styleTwo为真,则执行此操作?

编辑

我想我解决了它。它能正常工作。不确定这是否是最好的方法:

<div id="div" [ngStyle]="styleOne && {'background-color': 'red'} || styleTwo && {'background-color': 'blue'}">
6个回答

273

对于单个样式属性,您可以使用以下语法:

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

如果 style1style2 都不是 true,我认为背景颜色不应该被设置。


由于问题标题提到了 ngStyle,因此这里是使用该指令的等效语法:

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

61

你可以在ngStyle中使用内联if:

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

在我看来,更好的方法是将背景颜色存储在变量中,然后将background-color设置为变量值:

[style.background-color]="myColorVaraible"

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

5
<ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>

2
[ngStyle]="{ 'top': yourVar === true ? widthColumHalf + 'px': '302px' }"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接