Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Else statement in Angular

How does angular2 propose to render

<div *ngFor="let todo of unfinishedTodos">
    {{todo.title}}
</div>

in case if unfinishedTodos.length >0

and text "empty" in another cases.

P.S.

<div *ngIf="unfinishedTodos && unfinishedTodos.length > 0">
    <div *ngFor="let todo of unfinishedTodos">
        {{todo.title}}
    </div>
</div>
<div *ngIf="!unfinishedTodos ||  unfinishedTodos.length <= 0">
    empty
</div>

looks ugly

like image 859
gstackoverflow Avatar asked Dec 21 '16 14:12

gstackoverflow


4 Answers

Syntax compatible with Angular 4.0 and beyond

<ng-template #elseTemplate>
  Content displayed if expression returns false
</ng-template>
<ng-container *ngIf="expression; else elseTemplate">
  Content displayed if expression returns true
</ng-container>

or

<ng-container *ngIf="expression; then thenBlock; else elseBlock"></ng-container>
<ng-template #thenBlock>
  Content displayed if expression returns true
</ng-template>
<ng-template #elseBlock>
  Content displayed if expression returns false
</ng-template>

Syntax compatible with Angular 2.0 and beyond

<ng-container *ngIf="expression">
    true
</ng-container>
<ng-container *ngIf="!expression">
    else
</ng-container>

Important

  • You can use e.g. <div>, or any other tag, instead of <ng-container>

  • <template> had been deprecated since 4.0 in favor of <ng-template> to avoid name collision with already existing tag.

like image 159
Michał Pietraszko Avatar answered Oct 20 '22 03:10

Michał Pietraszko


With new Angular 4.0.0 syntax for else statement looks like this:

<div *ngIf="unfinishedTodos && unfinishedTodos.length > 0; else empty">
   <div *ngFor="let todo of unfinishedTodos">
      {{todo.title}}
   </div>
</div>
<ng-template #empty>
   empty
</ng-template >
like image 41
Matej Maloča Avatar answered Oct 20 '22 05:10

Matej Maloča


Try this

<div *ngFor="let todo of unfinishedTodos">
    {{todo.title}}
</div>
<div *ngIf="!unfinishedTodos?.length">
    empty
</div>
like image 21
Sergey Sokolov Avatar answered Oct 20 '22 04:10

Sergey Sokolov


CSS solution

<style>
    .empty { display: none; }
    .empty:only-child { display: block; }
</style>

<div>
    <div *ngFor="let todo of unfinishedTodos">
        {{todo.title}}
    </div>
    <div class="empty">
        empty
    </div>
</div>
like image 44
mr.Deviant Avatar answered Oct 20 '22 04:10

mr.Deviant