首页 > 其他 > 详细

ANGULAR :NGIF 的ELSE用法

时间:2020-07-29 01:55:49      阅读:81      评论:0      收藏:0      [点我收藏+]

1.首先我们看一下 *ngIf的用法

 <div *ngIf="display"> hello world </div>

在display为true 的时候,会显示 hello world,如果想要在为false的时候展现另一个内容的时候时候呢?

 <div *ngIf="!display"> world</div>

虽然上种写法可以达到需求,但相对麻烦点,这时候我们可以使用 *ngIf ;else 的写法,

2.ngIf 的else 的使用

可以使用一个不会展示在内容上的<ng-template></ng-template>区块

 <div *ngIf="isMobile; else notMobile">close</div>
                <ng-template #notMobile>
                 <div> menu</div>
                </ng-template>

这个时候 当ngIf逻辑为false 时,notMobile这个<ng-template>内的 <div>menu</div>来取代close,就可以达到else 的效果了。

你以为这样就结束了吗?No No No

 

3. 在一个模版中可以共用ng-template

上文提到的是一个简单的else使用场景,在事实上,多个ngIf的else 可以共用同一个ng-template;

<div *ngIf="isMobile; else notMobile">close</div>
<div *ngIf="isOpen; else notMobile">open</div>
        <ng-template #notMobile>
                 <div> menu</div>
        </ng-template>

上述过程中,我们只建立一个<ng-template>并且只有一个 notMobile,当模版内的其他地方有else 需求时,都可以使用notMobile里的内容,就不用为每个*ngIf都建立一个<ng-template>。

ANGULAR :NGIF 的ELSE用法

原文:https://www.cnblogs.com/junjun-001/p/13394212.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!