I'm trying to load pictureA or pictureB.
My first solution is like this:
<img *ngIf="my_picture" src="{{my_picture}}" width="180" height="80" >
<img *ngIf="default_picture && !my_picture" src="{{default_picture}}">
But I would like to use if-else like on API Reference:
<div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template>
So, I'm trying to do it like this:
<div *ngIf="my_picture; else elseBlock">
<img src="{{my_picture}}" >
</div>
<ng-template #elseBlock>
<img src="{{default_picture}}" >
</ng-template>
But I'm getting a big exception stack trace:
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 andall directives are listed in the "@NgModule.declarations". (" -->
[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
How can I implement a simple if-else block?
ngIf/Else syntax is not available in angular 2 but is available in angular 4
For angular 2, you need to use ngIf two times, and in second time you negate the value being compared (not using the !=, but having ampersand with the value)
<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>
For angular 4 onwards
<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>
**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>