如何在* ngIf语句中包含多个案例?我已经习惯了Vue或Angular 1有if,else if和else,但似乎Angular 4只有一个真(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中都不受支持,那么建议用这样的条件构造代码的方法是什么?
4 回答
另一种选择是筑巢条件
你可以使用:
除非ng-container部件对你的设计很重要,我想 .
这是一个Plunker
这似乎是最干净的方法
在模板中:
注意,当条件涉及不同的变量时,它是 works like a proper else if statement should (一次只有1个案例是真的) . 在这种情况下,其他一些答案无效 .
抛开:天哪,这是一些非常难看的模板代码......
您可以使用基于sitaution的多种方式: