如何使用* ngIf else?

如何使用* ngIf else?

我正在使用Angular,我希望*ngIf else在此示例中使用(自版本4起可用):

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

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


翻翻过去那场雪
浏览 3419回答 3
3回答

收到一只叮咚

角4和5:使用else:<div&nbsp;*ngIf="isValid;else&nbsp;other_content"> &nbsp;&nbsp;&nbsp;&nbsp;content&nbsp;here&nbsp;...</div><ng-template&nbsp;#other_content>other&nbsp;content&nbsp;here...</ng-template>你也可以用then else:<div&nbsp;*ngIf="isValid;then&nbsp;content&nbsp;else&nbsp;other_content">here&nbsp;is&nbsp;ignored</div>&nbsp;&nbsp;&nbsp;&nbsp;<ng-template&nbsp;#content>content&nbsp;here...</ng-template><ng-template&nbsp;#other_content>other&nbsp;content&nbsp;here...</ng-template>或then单独:<div&nbsp;*ngIf="isValid;then&nbsp;content"></div>&nbsp;&nbsp;&nbsp;&nbsp;<ng-template&nbsp;#content>content&nbsp;here...</ng-template>演示:Plunker细节:<ng-template>:是Angular自己的<template>标签实现,根据MDN:HTML&nbsp;<template>元素是一种用于保存客户端内容的机制,该内容在加载页面时不会呈现,但随后可以在运行时使用JavaScript进行实例化。

扬帆大鱼

在Angular 4.xx中&nbsp;您可以以四种方式使用ngIf来实现简单的if else过程:只需使用If<div&nbsp;*ngIf="isValid"> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;isValid&nbsp;is&nbsp;true</div>使用If with Else(请注意templateName)<div&nbsp;*ngIf="isValid;&nbsp;else&nbsp;templateName"> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;isValid&nbsp;is&nbsp;true</div><ng-template&nbsp;#templateName> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;isValid&nbsp;is&nbsp;false</ng-template>使用If with Then(请注意templateName)<div&nbsp;*ngIf="isValid;&nbsp;then&nbsp;templateName"> &nbsp;&nbsp;&nbsp;&nbsp;Here&nbsp;is&nbsp;never&nbsp;showing</div><ng-template&nbsp;#templateName> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;isValid&nbsp;is&nbsp;true</ng-template>使用If with Then和Else<div&nbsp;*ngIf="isValid;&nbsp;then&nbsp;thenTemplateName&nbsp;else&nbsp;elseTemplateName"> &nbsp;&nbsp;&nbsp;&nbsp;Here&nbsp;is&nbsp;never&nbsp;showing</div><ng-template&nbsp;#thenTemplateName> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;isValid&nbsp;is&nbsp;true</ng-template><ng-template&nbsp;#elseTemplateName> &nbsp;&nbsp;&nbsp;&nbsp;If&nbsp;isValid&nbsp;is&nbsp;false</ng-template>提示:ngIf计算表达式,然后&nbsp;在表达式分别为truthy或falsy时将then或else模板呈现在其位置。通常是:然后&nbsp;template是ngIf的内联模板,除非绑定到不同的值。除非绑定,否则else模板为空。

Cats萌萌

为了使用observable,如果可观察数组由数据组成,我通常会这样做。<div&nbsp;*ngIf="(observable$&nbsp;|&nbsp;async)&nbsp;as&nbsp;listOfObject&nbsp;else&nbsp;emptyList"> &nbsp;&nbsp;&nbsp;<div&nbsp;> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.... &nbsp;&nbsp;&nbsp;&nbsp;</div></div> &nbsp;<ng-template&nbsp;#emptyList> &nbsp;&nbsp;&nbsp;<div&nbsp;> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... &nbsp;&nbsp;&nbsp;&nbsp;</div></ng-template>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS