如何在ngIf中使用相同的模板

时间:2017-09-06 19:34:25

标签: javascript html angular

我有很多条件要显示相同的模板。例如:

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

是否可以使用此html元素:

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

并放在某处,然后在*ngIf中按名称/引用调用此html元素?例如:

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

2 个答案:

答案 0 :(得分:2)

实际上ngIf有一个很酷的&#39;属性then,您可以使用:

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

由于<template>已被弃用,请改为使用<ng-template><ng-container>。 您可以删除模板中的第二个ngIf,因为第一个就足够了。

Stackblitz

答案 1 :(得分:1)

是的,可以使用 NgIf DIRECTIVE

有条件地包含基于表达式值的模板。

ngIf评估表达式,然后当表达式分别为真或假时,将then或else模板呈现在其位置。通常是:

  • 然后template是ngIf的内联模板,除非绑定到a 不同的价值。
  • else模板除非被绑定,否则为空。

以下是snapcode:

<div *ngIf="condition; then thenBlock else elseBlock"></div>

    <ng-template #thenBlock></ng-template>
    <ng-template #elseBlock></ng-template> 

Angular4 ngIf会为您提供更多详细信息。

希望plunker能帮到你