我使用Angular,我想在这个例子中使用*ngIf else
(从第4版开始可用)。
<div *ngIf="isValid">
content here ...
</div>
<div *ngIf="!isValid">
other content here...
</div>
我怎样才能用 "ngIf else "实现同样的行为?
Angular 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>
演示 :
[****][1]。
详情:
<ng-template>
:是Angular自己实现的<template>
标签,根据[MDN][2] 。
HTML
<template>
元素是一种机制,用于保存客户端的 内容的机制,这些内容在页面加载时不会被渲染,但可能会被 随后在运行时使用JavaScript实例化的内容。
"bindEmail"它将检查电子邮件是否可用,如果电子邮件存在,将显示注销,否则将显示登录。
<li *ngIf="bindEmail;then logout else login"></li>
<ng-template #logout><li><a routerLink="/logout">Logout</a></li></ng-template>
<ng-template #login><li><a routerLink="/login">Login</a></li></ng-template>
在Angular 4.0中,"if...else "的语法与Java中的条件运算符非常相似。
在Java中你使用"condition?stmnt1:stmnt2"
。
在Angular 4.0中你使用*ngIf="condition;then stmnt1 else stmnt2"
。