Angular 4 * ng如果其他if? [英] Angular 4 *ngIf else if?
问题描述
我如何在一个* 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>第一个< / ng-template>
< ng-template#second> Second< / ng-template>
< ng-template#third>第三< / ng-template>
但是我想要有多个条件(类似):
< ng-container * ngIf =foo === 1; then first; foo === 2; then second else third>< / ng -container>
< ng-template#first>第一个< / ng-template>
< ng-template#second> Second< / ng-template>
< ng-template#third>第三< / ng-template>
但是我最后不得不使用ngSwitch,这感觉像是一个黑客:
< ng-container [ngSwitch] =true>
< div * ngSwitchCase =foo === 1>第一个< / div>
< div * ngSwitchCase =bar === 2>第二个< / div>
< div * ngSwitchDefault>第三< / div>
< / ng-container>
另外,它似乎有很多我习惯从Angular 1和Vue中得到的语法在Angular 4中不被支持,那么以这样的条件构建我的代码的推荐方式是什么?
另一个替代方案是嵌套条件 < ng-container * ngIf =foo === 1; else second><< ; / NG-容器>
< ng-template#second>
< ng-container * ngIf =foo === 2; else third>< / ng-container>
< / ng-template>
< ng-template#third>< / ng-template>
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>
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>
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?
Another alternative is to nest conditions
<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>
这篇关于Angular 4 * ng如果其他if?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!