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

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

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

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


当前回答

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

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

其他回答

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

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

**ngIf else** <div *ngIf="isConditionTrue;else other_condition"> your content here </div> <ng-template #other_condition>other content here...</ng-template> **ngIf then else** <div *ngIf="isConditionTrue;then content else other_content">here is ignored</div> <ng-template #content>content here...</ng-template> <ng-template #other_content>other content here...</ng-template> **ngIf then** <div *ngIf="isConditionTrue;then content"></div> <ng-template #content>content here...</ng-template>

在Angular 4.x.x中

你可以用四种方式使用ngIf来实现一个简单的if-else过程:

Just use If <div *ngIf="isValid"> If isValid is true </div> Using If with Else (please notice to templateName) <div *ngIf="isValid; else templateName"> If isValid is true </div> <ng-template #templateName> If isValid is false </ng-template> Using If with Then (please notice to templateName) <div *ngIf="isValid; then templateName"> Here is never showing </div> <ng-template #templateName> If isValid is true </ng-template> Using If with Then and Else <div *ngIf="isValid; then thenTemplateName else elseTemplateName"> Here is never showing </div> <ng-template #thenTemplateName> If isValid is true </ng-template> <ng-template #elseTemplateName> If isValid is false </ng-template>

提示:ngIf对表达式求值,然后呈现then或else 当表达式分别为真或假时,模板在其位置。 通常: 那么template就是ngIf的内联模板,除非绑定到不同的值。 除非绑定,否则模板为空白。

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

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

or

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

这里有一些关于Angular的NgIf和使用else语句的漂亮而干净的语法。简而言之,你将在元素上声明一个ElementRef,然后在else块中引用它:

<div *ngIf="isLoggedIn; else loggedOut">
   Welcome back, friend.
</div>

<ng-template #loggedOut>
  Please friend, login.
</ng-template>

我从NgIf, Else, Then中取了这个例子,我发现这个例子解释得很好。

它还演示了使用<ng-template>语法:

<ng-template [ngIf]="isLoggedIn" [ngIfElse]="loggedOut">
  <div>
    Welcome back, friend.
  </div>
</ng-template>

<ng-template #loggedOut>
  <div>
    Please friend, login.
  </div>
</ng-template>

并且使用<ng-container>如果这是你想要的:

<ng-container
  *ngIf="isLoggedIn; then loggedIn; else loggedOut">
</ng-container>

<ng-template #loggedIn>
  <div>
    Welcome back, friend.
  </div>
</ng-template>
<ng-template #loggedOut>
  <div>
    Please friend, login.
  </div>
</ng-template>

Source来自Angular的NgIf和Else语法。