Cómo usar *ngIf else?


Estoy usando Angular y quiero usar *ngIf else (disponible desde la versión 4) en este ejemplo:

<div *ngIf="isValid">
  content here ...
</div>

<div *ngIf="!isValid">
 other content here...
</div>

¿Cómo puedo lograr el mismo comportamiento con ngIf else?

Author: Alexander Abakumov, 2017-03-24

10 answers

Angular 4 y 5:

Usando else:

<div *ngIf="isValid;else other_content">
    content here ...
</div>

<ng-template #other_content>other content here...</ng-template>

También puedes usar then else:

<div *ngIf="isValid;then content else other_content">here is ignored</div>    
<ng-template #content>content here...</ng-template>
<ng-template #other_content>other content here...</ng-template>

O then solo :

<div *ngIf="isValid;then content"></div>    
<ng-template #content>content here...</ng-template>

Demo :

Plunker

Detalles:

<ng-template>: es la propia implementación de Angular de la etiqueta <template> que está de acuerdo con MDN :

El elemento HTML <template> es un mecanismo para mantener el lado del cliente contenido que no se debe representar cuando una página es cargado, pero puede posteriormente ser instanciado durante el tiempo de ejecución usando JavaScript.

 619
Author: Bougarfaoui El houcine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-25 06:55:34

En Angular 4.x. x Puede usar ngIf de cuatro maneras para lograr un procedimiento simple if else:

  1. Solo Use Si

    <div *ngIf="isValid">
        If isValid is true
    </div>
    
  2. Usando Si con Else (Por favor, observe a templateName)

    <div *ngIf="isValid; else templateName">
        If isValid is true
    </div>
    
    <ng-template #templateName>
        If isValid is false
    </ng-template>
    
  3. Usando Si con Entonces (Por favor note a templateName)

    <div *ngIf="isValid; then templateName">
        Here is never showing
    </div>
    
    <ng-template #templateName>
        If isValid is true
    </ng-template>
    
  4. Usando If con Then y Else

    <div *ngIf="isValid; then thenTemplateName else elseTemplateName">
        Here is never showing
    </div>
    
    <ng-template #thenTemplateName>
        If isValid is true
    </ng-template>
    
    <ng-template #elseTemplateName>
        If isValid is false
    </ng-template>
    

Consejo: ngIf evalúa la expresión y, a continuación, hace que la entonces o else plantilla en su lugar cuando la expresión es veraz o falsa respectivamente. Normalmente el:

  • entonces la plantilla es la plantilla inline de ngIf a menos que esté vinculada a un valor diferente.
  • else la plantilla está en blanco a menos que esté enlazada.
 110
Author: John Henckel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-17 17:34:11

Para trabajar con observable, esto es lo que suelo hacer para mostrar si la matriz observable consiste en datos.

<div *ngIf="(observable$ | async) as listOfObject else emptyList">
   <div >
        ....
    </div>
</div>
 <ng-template #emptyList>
   <div >
        ...
    </div>
</ng-template>
 9
Author: Ah Hiang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-29 09:03:15

"bindEmail" comprobará que el correo electrónico está disponible o no. si el correo electrónico existe, se mostrará Logout, de lo contrario, Se mostrará Login

<li *ngIf="bindEmail;then logout else login"></li>
<ng-template #logout><li><a routerLink="/logout">Logout</a></li></ng-template>
<ng-template #login><li><a routerLink="/login">Login</a></li></ng-template>
 6
Author: Prashant Shrivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-23 13:17:59

En Angular 4.0 if..else la sintaxis es bastante similar a los operadores condicionales en Java.

En Java se usa "condition?stmnt1:stmnt2".

En Angular 4.0 se usa *ngIf="condition;then stmnt1 else stmnt2".

 4
Author: Er Amit Gaikwad Patil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-02 19:25:36

El valor resultante de la expresión Ngif no será solo el verdadero o falso booleano

Si la expresión es solo un objeto, todavía lo evalúa como verdad.

Si el objeto no está definido, o no existe, entonces ngif lo evaluará como falsedad.

El uso común es si un objeto cargado, existe, a continuación, mostrar el contenido de este objeto, de lo contrario mostrar "loading.......".

 <div *ngIf="!object">
     Still loading...........
 </div>

<div *ngIf="object">
     <!-- the content of this object -->

           object.info, object.id, object.name ... etc.
 </div>

Otro ejemplo:

  things = {
 car: 'Honda',
 shoes: 'Nike',
 shirt: 'Tom Ford',
 watch: 'Timex'
 };

 <div *ngIf="things.car; else noCar">
  Nice car!
 </div>

<ng-template #noCar>
   Call a Uber.
</ng-template>

 <!-- Nice car ! -->

Ejemplo anterior:

<div *ngIf="things.car; let car">
   Nice {{ car }}!
 </div>
<!-- Nice Honda! -->

Ngif plantilla

Ngif angular 4

 4
Author: hoogw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-11 18:00:54
<div *ngIf="this.model.SerialNumber != '';then ConnectedContent else DisconnectedContent" class="data-font">    </div>

<ng-template #ConnectedContent class="data-font">Connected</ng-template>
<ng-template #DisconnectedContent class="data-font">Disconnected</ng-template>
 0
Author: Amir Twito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-17 15:44:35

En Angular 4, 5 y 6

Simplemente podemos crear una variable de referencia de plantilla [2] y vincule eso a la condición else dentro de una directiva *ngIf

Las posibles Sintaxis [1] son:

<!-- Only If condition -->
<div *ngIf="condition">...</div>
<!-- or -->
<ng-template [ngIf]="condition"><div>...</div></ng-template>


<!-- If and else conditions -->
<div *ngIf="condition; else elseBlock">...</div>
<!-- or -->
<ng-template #elseBlock>...</ng-template>

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


<!-- If and else conditions (storing condition value locally) -->
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template>

DEMO: https://stackblitz.com/edit/angular-feumnt?embed=1&file=src/app/app.component.html

Fuentes:

  1. https://angular.io/api/common/NgIf#syntax
  2. https://angular.io/guide/template-syntax#template-reference-variables--var -
 0
Author: Kalpesh Panchal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-08 20:24:34

Sé que esto ha pasado un tiempo, pero quiero agregarlo si ayuda. La forma en que lo hice es tener dos banderas en el componente y dos ngIfs para las dos banderas correspondientes.

Fue simple y funcionó bien con el material, ya que ng-plantilla y material no funcionaban bien juntos.

 0
Author: user1707141,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 07:29:56

Sintaxis para ngIf/Else

<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<ng-template #elseBlock>Falsy condition</ng-template>

introduzca la descripción de la imagen aquí

Usando la sintaxis ngIf / Else/ Then explicit

Para añadir entonces plantilla solo tenemos que enlazarla a una plantilla explícitamente.

<div *ngIf=”condition; then thenBlock else elseBlock”> ... </div> 
<ng-template #thenBlock>Then template</ng-template>
<ng-template #elseBlock>Else template</ng-template>

introduzca la descripción de la imagen aquí

Observables con ngIf y Tubería Asíncrona

Para más detalles

introduzca la descripción de la imagen aquí

 0
Author: Lyes CHIOUKH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-11 08:10:13