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

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

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

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


当前回答

对于Angular 9/8

源链接及示例

    export class AppComponent {
      isDone = true;
    }

1) * ngIf

    <div *ngIf="isDone">
      It's Done!
    </div>

    <!-- Negation operator-->
    <div *ngIf="!isDone">
      It's Not Done!
    </div>

2) *ngIf和Else

    <ng-container *ngIf="isDone; else elseNotDone">
      It's Done!
    </ng-container>

    <ng-template #elseNotDone>
      It's Not Done!
    </ng-template>

3) *ngIf, Then和Else

    <ng-container *ngIf="isDone;  then iAmDone; else iAmNotDone">
    </ng-container>

    <ng-template #iAmDone>
      It's Done!
    </ng-template>

    <ng-template #iAmNotDone>
      It's Not Done!
    </ng-template>

其他回答

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的可观察对象

欲知详情

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

在HTML标签或模板上使用if条件有两种可能:

*ngIf指令来自CommonModule,在HTML标签上; if - else

你可以使用<ng-container>和<ng-template>来实现:

<ng-container *ngIf="isValid; then template1 else template2"></ng-container>

<ng-template #template1>
     <div>Template 1 contains</div>
</ng-template>

<ng-template #template2>
     <div>Template 2 contains </div>
</ng-template>

你可以在下面找到StackBlitz现场演示:

现场演示

<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>