为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用* ngIf else?

如何使用* ngIf else?

翻翻过去那场雪 2019-08-29 09:22:49
如何使用* ngIf else?我正在使用Angular,我希望*ngIf else在此示例中使用(自版本4起可用):<div *ngIf="isValid">   content here ...</div><div *ngIf="!isValid">  other content here...</div>我怎样才能实现同样的行为ngIf else?
查看完整描述

3 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

角4和5

使用else

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

then单独:

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

演示:

Plunker

细节:

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

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


查看完整回答
反对 回复 2019-08-29
?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

在Angular 4.xx中 您可以以四种方式使用ngIf来实现简单的if else过程:

  1. 只需使用If

    <div *ngIf="isValid">
        If isValid is true</div>
  2. 使用If with Else(请注意templateName

    <div *ngIf="isValid; else templateName">
        If isValid is true</div><ng-template #templateName>
        If isValid is false</ng-template>
  3. 使用If with Then(请注意templateName

    <div *ngIf="isValid; then templateName">
        Here is never showing</div><ng-template #templateName>
        If isValid is true</ng-template>
  4. 使用If with Then和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计算表达式,然后 在表达式分别为truthy或falsy时将thenelse模板呈现在其位置。通常是:

  • 然后 template是ngIf的内联模板,除非绑定到不同的值。

  • 除非绑定,否则else模板为空。


查看完整回答
反对 回复 2019-08-29
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

为了使用observable,如果可观察数组由数据组成,我通常会这样做。

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


查看完整回答
反对 回复 2019-08-29
  • 3 回答
  • 0 关注
  • 3405 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信