Search code examples
javascripthtmlangulartypescriptangular-ng-if

How to use the same template in ngIf


I have many conditions to show the same template. For example:

<template [ngIf]="item.url.indexOf('http') == -1">
  <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" >             
    <span class="media-body media-middle" *ngIf="isUserLoggedIn == true">{{item.name}}</span>
  </a> 
  <p>Hello, World!</p>
</template>

<template [ngIf]="item.url.indexOf('http') == 0">
  <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" >             
    <span class="media-body media-middle" *ngIf="isUserLoggedIn == true">{{item.name}}</span>
  </a> 
  <p>Hello, World!</p>
</template>

<template [ngIf]="item.url.indexOf('http') == 1">
  <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" >             
    <span class="media-body media-middle" *ngIf="isUserLoggedIn == true">{{item.name}}</span>
  </a> 
  <p>Hello, World!</p>
</template>

<template [ngIf]="item.url.indexOf('http') == 2">
  <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" >             
    <span class="media-body media-middle" *ngIf="isUserLoggedIn == true">{{item.name}}</span>
  </a> 
  <p>Hello, World!</p>
</template>

Is it possible to take this html elements:

<a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" >             
   <span class="media-body media-middle" *ngIf="isUserLoggedIn == true">
        {{item.name}}
   </span>
</a> 
<p>Hello, World!</p>

and put somewhere and then just call this html elements by name/reference in *ngIf? For example:

<template [ngIf]="item.url.indexOf('http') == 2">
  <!--reference to the repeatable code-->
</template>

Solution

  • Actually ngIf has a 'cool' attribute, then, that you could make use of:

      <ng-container *ngIf="item.url.indexOf('http') === -1; then myTemplate">
      </ng-container>
    
      <ng-container *ngIf="item.url.indexOf('http') === 0; then myTemplate">
      </ng-container>
    
      <ng-container *ngIf="item.url.indexOf('http') === 1; then myTemplate">
      </ng-container>
    
      <ng-template #myTemplate>
        <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" >             
           <span class="media-body media-middle">{{item.name}}</span>
        </a> 
        <p>Hello, World!</p>
      </ng-template>
    

    As <template> has been deprecated, use <ng-template> instead or <ng-container>. You can remove the second ngIf in the template as the first is sufficient.

    Stackblitz