ngIf-else in the template

I am trying to upload an image pictureAor image pictureBMy first solution is 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- elseas on the 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 get a big trace of the exception stack:

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 "@ 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 block if- else?

+5
source share
3 answers

You must use 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

+10
source

NgIf / Else syntax not available in angular 2 but available in angular 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>
+8
**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>
+2
source

Source: https://habr.com/ru/post/1016698/


All Articles