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 and
all 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?
As we all programmers know if or if else condition is used to create conditional statements so in angular template we can also use the if else but for elseif there is no direct way but we can use alternate way.
A shorthand form of the directive, *ngIf="condition" , is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.
You should be using 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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With