* ng如果在模板中,否则
在*ngIf
语句中如何处理多个案例?我已经习惯了Vue或Angular 1具有if
,else if
和else
的功能,但似乎Angular 4仅具有true
(if
)和false
(else
)条件.
How would I have multiple cases in an *ngIf
statement? 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
) and false
(else
) condition.
根据文档,我只能这样做:
According to the documentation, I can only do:
<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>
但是我想有多个条件(类似):
But I want to have multiple conditions (something like):
<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
,感觉就像是一个黑客:
But I'm ending up having to use ngSwitch
, which feels like a hack:
<ng-container [ngSwitch]="true">
<div *ngSwitchCase="foo === 1">First</div>
<div *ngSwitchCase="bar === 2">Second</div>
<div *ngSwitchDefault>Third</div>
</ng-container>
或者,似乎我从Angular 1和Vue习以为常的许多语法在Angular 4中均不受支持,那么采用这种条件构造代码的推荐方法是什么?>
Alternately, it seems like a lot of the syntaxes I've got used to from Angular 1 and Vue aren't supported in Angular 4, so what would be the recommended way to structure my code with conditions like this?
另一种方法是嵌套条件
<ng-container *ngIf="foo === 1;else second"></ng-container>
<ng-template #second>
<ng-container *ngIf="foo === 2;else third"></ng-container>
</ng-template>
<ng-template #third></ng-template>