我正在尝试加载pictureA
或pictureB
。
我的第一个解决方案是这样的:
<img *ngIf="my_picture" src="{{my_picture}}" width="180" height="80" >
<img *ngIf="default_picture && !my_picture" src="{{default_picture}}">
但我想在API参考上使用if
- else
:
<div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template>
所以,我试图这样做:
<div *ngIf="my_picture; else elseBlock">
<img src="{{my_picture}}" >
</div>
<ng-template #elseBlock>
<img src="{{default_picture}}" >
</ng-template>
但是我得到了一个很大的异常堆栈跟踪:
zone.js:388 Unhandled Promise rejection: Template parse errors: Can't bind to 'ngIfElse' since it isn't a known property of 'div'. (" --> <div [ERROR ->]*ngIf="my_picture; else elseBlock"> <img src="{{my_picture}}"): UserComponent@15:13 Property binding ngIfElse not used by any directive on an embedded template. Make sure that the property name is spelled correctly and
所有指令都列在&#34; @ NgModule.declarations&#34;中。 (&#34; - &GT;
[ERROR ->]<div *ngIf="my_picture; else elseBlock"> <img src="{{my_picture}}" width="180" height="8"): UserComponent@15:8 'ng-template' is not a known element
如何实施简单的if
- else
阻止?
答案 0 :(得分:10)
您应该使用ng-template
<ng-template #loading>Failed to do something wrong...</ng-template>
<div *ngIf="userObservable;else loading;">
Aravind is here
</div>
<button (click)="userObservable = !userObservable">Click to toggle</button>
</div>
<强> LIVEDEMO 强>
答案 1 :(得分:9)
ngIf / Else语法在角度2中不可用,但在角度4
中可用对于角度2,你需要使用ngIf两次,并且在第二次你否定被比较的值(不是使用!=,而是使用带符号的&符号)
<div class="text-center" *ngIf='userName'> Hello {{userName}}, how are you </div>
<div class="text-center" *ngIf='userName == ""'> Hello, please login to access the app</div>
对于角4向前
<div *ngIf="userName; else showLoginRequestMessage">
Hello {{userName}}, how are you
</div>
<ng-template #showLoginRequestMessage>
<div class="text-center"> Hello, please login to access the app</div>
</ng-template>
答案 2 :(得分:2)
**example 1 ngIf**
<div *ngIf="condition">..</div>
<div template="ngIf condition">..</div>
**example 1.i ngIf**
<ng-template [ngIf]="condition"><div>..</div></ng-template>
**example 2 else block**
<div *ngIf="condition; else elseBlock">....</div>
<ng-template #elseBlock>....</ng-template>
**example 3 then and else block**
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>......</ng-template>
<ng-template #elseBlock>......</ng-template>