ngIf-else在模板中

Rom*_*Kap 6 if-statement angular

我正在尝试加载pictureApictureB.我的第一个解决方案是这样的:

 <img *ngIf="my_picture" src="{{my_picture}}" width="180" height="80" >
 <img *ngIf="default_picture && !my_picture" src="{{default_picture}}">
Run Code Online (Sandbox Code Playgroud)

但我想使用if- else就像API参考:

<div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template>
Run Code Online (Sandbox Code Playgroud)

所以,我试着这样做:

 <div *ngIf="my_picture; else elseBlock">
     <img src="{{my_picture}}" >
 </div>
 <ng-template #elseBlock>
      <img src="{{default_picture}}" >
 </ng-template>
Run Code Online (Sandbox Code Playgroud)

但是我得到了一个很大的异常堆栈跟踪:

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
Run Code Online (Sandbox Code Playgroud)

所有指令都列在"@ 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
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现一个简单的if- else块?

Ara*_*ind 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>
Run Code Online (Sandbox Code Playgroud)

LIVEDEMO


Nit*_*ngh 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>
Run Code Online (Sandbox Code Playgroud)

对于角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>
Run Code Online (Sandbox Code Playgroud)