我使用的是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>

其他回答

要使用可观察对象,如果可观察对象数组由数据组成,我通常会这样显示。

<div *ngIf="(observable$ | async) as listOfObject else emptyList">
   <div >
        ....
    </div>
</div>
 <ng-template #emptyList>
   <div >
        ...
    </div>
</ng-template>

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

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

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

还可以使用JavaScript的短三元条件运算符吗?在Angular中是这样的:

{{doThis() ? 'foo' : 'bar'}}

or

<div [ngClass]="doThis() ? 'foo' : 'bar'">

所以,这实际上并没有使用ng-if,但许多建议似乎是处理在条件语句中编写文本。我认为这种方法是用最少的代码或复杂性来做到这一点的最好方法。你来评判吧。

<div>{{variable == null ? 'Testing1' : 'Testing2'}}<div>
OR
<div>{{variable == null ? var1 : var2 }}<div>

只需从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>