/ / Angular2 ngIf-else - angolare, if-statement

Angular2 ngIf-else - angolare, if-statement

Sto cercando di caricare l'immagine A o l'immagine B. La mia prima soluzione è così:

 <img *ngIf="my_picture" src="/images/{{my_picture}}" width="180" height="80" >
<img *ngIf="default_picture && !my_picture" src="{{default_picture}}">

Ma mi piacerebbe usare if-else come su API-Reference:

<div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template>

Quindi lo faccio così:

 <div *ngIf="my_picture; else elseBlock">
<img src="/images/{{my_picture}}" >
</div>
<ng-template #elseBlock>
<img src="/images/{{default_picture}}" >
</ng-template>

Ma ottengo un grande stack di eccezioni:

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="/images/{{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

tutte le direttive sono elencate in "@ NgModule.declarations". (" ->

        [ERROR ->]<div *ngIf="my_picture; else elseBlock">
<img src="/images/{{my_picture}}" width="180" height="8"): UserComponent@15:8
"ng-template" is not a known element

Come posso reliaze semplice blocco if-else?

risposte:

10 per risposta № 1

Dovresti usare 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>

DIMOSTRAZIONE DAL VIVO


7 per risposta № 2

ngIf / Else la sintassi non è disponibile nell'angolare 2 ma è disponibile nell'angolare 4

Per angular 2, è necessario utilizzare ngIf due volte, e in una seconda volta si annulla il valore da confrontare (non si usa il! =, Ma con la e commerciale con il valore)

<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>

Per angolare 4 in poi

<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 per risposta № 3
**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>