我使用的是Angular,我想在这个例子中使用*ngIf else(从版本4开始可用):
<div *ngIf="isValid">
content here ...
</div>
<div *ngIf="!isValid">
other content here...
</div>
我怎样才能用ngIf else实现同样的行为?
我使用的是Angular,我想在这个例子中使用*ngIf else(从版本4开始可用):
<div *ngIf="isValid">
content here ...
</div>
<div *ngIf="!isValid">
other content here...
</div>
我怎样才能用ngIf else实现同样的行为?
当前回答
在HTML标签或模板上使用if条件有两种可能:
*ngIf指令来自CommonModule,在HTML标签上; if - else
其他回答
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实例化。
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的可观察对象
欲知详情
<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>
ngif表达式的结果值不只是布尔值true或false。
如果表达式只是一个对象,它仍然会将其评估为真实性。
如果对象未定义或不存在,则ngif将其赋值为false。
常用的用法是如果一个对象加载后,存在,则显示该对象的内容,否则显示“加载中.......”。
<div *ngIf="!object">
Still loading...........
</div>
<div *ngIf="object">
<!-- the content of this object -->
object.info, object.id, object.name ... etc.
</div>
另一个例子:
things = {
car: 'Honda',
shoes: 'Nike',
shirt: 'Tom Ford',
watch: 'Timex'
};
<div *ngIf="things.car; else noCar">
Nice car!
</div>
<ng-template #noCar>
Call a Uber.
</ng-template>
<!-- Nice car ! -->
另一个例子:
<div *ngIf="things.car; let car">
Nice {{ car }}!
</div>
<!-- Nice Honda! -->
ngif模板
恩吉夫角 4
在Angular 4.0中,if..else语法非常类似于Java中的条件操作符。
在Java中,你使用“条件?stmnt1:stmnt2”。
在Angular 4.0中,你使用*ngIf="condition;then stmnt1 else stmnt2"。