我如何在 *ngIf
语句中有多个案例? I’m used to Vue or Angular 1 with having an if
, else if
, and else
, but it seems like Angular 4 only has a true
( if
) 和 false
( else
) 条件。
根据文档,我只能这样做:
<ng-container *ngIf="foo === 1; then first else second"></ng-container>
<ng-template #first>First</ng-template>
<ng-template #second>Second</ng-template>
<ng-template #third>Third</ng-template>
但我想有多个条件(比如):
<ng-container *ngIf="foo === 1; then first; foo === 2; then second else third"></ng-container>
<ng-template #first>First</ng-template>
<ng-template #second>Second</ng-template>
<ng-template #third>Third</ng-template>
但我最终不得不使用 ngSwitch
,这感觉就像一个黑客:
<ng-container [ngSwitch]="true">
<div *ngSwitchCase="foo === 1">First</div>
<div *ngSwitchCase="bar === 2">Second</div>
<div *ngSwitchDefault>Third</div>
</ng-container>
或者,在 Angular 4 中似乎不支持我从 Angular 1 和 Vue 中习惯的许多语法,那么推荐使用这样的条件来构造我的代码的方法是什么?
原文由 user358089 发布,翻译遵循 CC BY-SA 4.0 许可协议
另一种选择是嵌套条件