我使用的是Angular,我想在这个例子中使用*ngIf else(从版本4开始可用):

<div *ngIf="isValid">
  content here ...
</div>

<div *ngIf="!isValid">
 other content here...
</div>

我怎样才能用ngIf else实现同样的行为?


当前回答

只需从Angular 8中添加新的更新。

For case if with else, we can use ngIf and ngIfElse. <ng-template [ngIf]="condition" [ngIfElse]="elseBlock"> Content to render when condition is true. </ng-template> <ng-template #elseBlock> Content to render when condition is false. </ng-template> For case if with then, we can use ngIf and ngIfThen. <ng-template [ngIf]="condition" [ngIfThen]="thenBlock"> This content is never showing </ng-template> <ng-template #thenBlock> Content to render when condition is true. </ng-template> For case if with then and else, we can use ngIf, ngIfThen, and ngIfElse. <ng-template [ngIf]="condition" [ngIfThen]="thenBlock" [ngIfElse]="elseBlock"> This content is never showing </ng-template> <ng-template #thenBlock> Content to render when condition is true. </ng-template> <ng-template #elseBlock> Content to render when condition is false. </ng-template>

其他回答

"bindEmail"将检查电子邮件是否可用。如果电子邮件存在,则登出将显示。否则将显示Login。

<li *ngIf="bindEmail;then logout else login"></li>
<ng-template #logout><li><a routerLink="/logout">Logout</a></li></ng-template>
<ng-template #login><li><a routerLink="/login">Login</a></li></ng-template>

在Angular 4、5和6中

我们可以简单地创建一个模板引用变量2,并将其链接到*ngIf指令中的else条件

可能的语法是:

<!-- Only If condition -->
<div *ngIf="condition">...</div>
<!-- or -->
<ng-template [ngIf]="condition"><div>...</div></ng-template>


<!-- If and else conditions -->
<div *ngIf="condition; else elseBlock">...</div>
<!-- or -->
<ng-template #elseBlock>...</ng-template>

<!-- If-then-else -->
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template>


<!-- If and else conditions (storing condition value locally) -->
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template>

演示: https://stackblitz.com/edit/angular-feumnt?embed=1&file=src/app/app.component.html

来源:

NgIf -指令 模板的语法

ngIf/Else的语法

<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<ng-template #elseBlock>Falsy condition</ng-template>

使用NgIf / Else/ Then显式语法

要添加then模板,只需显式地将其绑定到模板。

<div *ngIf=”condition; then thenBlock else elseBlock”> ... </div>
<ng-template #thenBlock>Then template</ng-template>
<ng-template #elseBlock>Else template</ng-template>

NgIf和Async Pipe的可观察对象

欲知详情

<div *ngIf="this.model.SerialNumber != '';then ConnectedContent else DisconnectedContent" class="data-font">    </div>

<ng-template #ConnectedContent class="data-font">Connected</ng-template>
<ng-template #DisconnectedContent class="data-font">Disconnected</ng-template>

在Angular 4.0中,if..else语法非常类似于Java中的条件操作符。

在Java中,你使用“条件?stmnt1:stmnt2”。

在Angular 4.0中,你使用*ngIf="condition;then stmnt1 else stmnt2"。