【发布时间】:2017-10-04 09:32:15
【问题描述】:
*ngIf 语句中如何处理多个案例?我习惯 Vue 或 Angular 1 有一个 if、else if 和 else,但似乎 Angular 4 只有一个 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 1 和 Vue 中习惯的很多语法似乎在 Angular 4 中不受支持,那么推荐使用什么方法来构建具有此类条件的代码?
【问题讨论】:
-
我认为你 hack 是最好的解决方案,因为它最具可读性。但是我已经意识到角度 switch 语句允许匹配多个条件,所以你不会得到真正的 elseif 逻辑。
标签: angular templates angular-ng-if