【问题标题】:Angular If statement for 3 cases3 种情况的 Angular If 语句
【发布时间】:2020-07-26 16:02:03
【问题描述】:

如何在 Angular 中编写适用于 3 个选项的 switch case 或 if 语句,

 if Boards.status==1 then "Approved"
 if Boards.status==2 then "Pending"
 if Boards.status==3 then "Rejected"

我已经尝试过了,但需要添加所有 3 个选项。

    <td>{{Boards.status==1 ? "Approved": "Pending" }}</td>

【问题讨论】:

  • 第二个条件需要用括号括起来:&lt;td&gt;{{Boards.status==1 ? "Approved": (Boards.status==2?"Pending":"Rejected") }}&lt;/td&gt;

标签: angular


【解决方案1】:

你可以试试这个:

<tr [ngSwitch=Boards.status]="switch_expression">
  <td *ngSwitchCase="1">Approved</td>
  <td *ngSwitchCase="2">Pending</td>
  <td *ngSwitchCase="3">Rejected</td>
  <td *ngSwitchDefault>...</td>
</tr>

请随时参考link

【讨论】:

  • 你也可以使用三元运算符
【解决方案2】:

你不能用三元运算符来做到这一点,但有几个选择。一种是用返回所需值的函数替换插值运算符之间的所有内容,该函数只是一些 if/else 语句。另一种方式是使用 ngif/else 模式 *ngIf else if in template 的一组 div 或 ng 容器。

更新: @Eliseo 指出您实际上可以使用三元运算符来做到这一点。从这个问题你可以这样做,我认为:

<td>{{Boards.status == 1 ? "Approved": Boards.status === 2 ? "Pending": "Rejected" }}</td>

接受的答案还有一个我忘记的好方法,就是使用ngSwitchCase

【讨论】:

  • 不,当然你可以使用三元运算符,只注意使用括号
  • @Eliseo 等等,你是对的,我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 2012-08-21
  • 2014-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2020-01-30
  • 1970-01-01
相关资源
最近更新 更多