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

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

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

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


当前回答

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

欲知详情

其他回答

你可以使用<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现场演示:

现场演示

Angular 4和Angular 5:

使用其他:

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

<ng-template #other_content>other content here...</ng-template>

你也可以用then else:

<div *ngIf="isValid;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>

或者独自一人:

<div *ngIf="isValid;then content"></div>
<ng-template #content>content here...</ng-template>

演示:

砰砰作响

细节:

<ng-template>:是Angular自己对<template>标签的实现,根据MDN:

HTML <template>元素是一种保存客户端的机制 加载页面时不呈现但可以呈现的内容 然后在运行时使用JavaScript实例化。

所以,这实际上并没有使用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>

我所采用的方法是在组件中有两个标志,并为对应的两个标志设置两个ngif。

它是简单的,并与ng-template和材料不一起工作很好。