![](/img/trans.png)
[英]In *ngIf directive: how to store returned value from a function in a variable and use it in the very same *ngIf?
[英]How to use the same template in ngIf
我有很多条件来显示相同的模板。 例如:
<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>
实际上ngIf有一个'酷'属性, 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
,因为第一个就足够了。
是的,可以使用NgIf DIRECTIVE
有条件地包括基于表达式值的模板。
ngIf计算表达式,然后当表达式分别为真或假时,将then或else模板呈现在其位置。 通常是:
下面是snapcode:
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock></ng-template>
<ng-template #elseBlock></ng-template>
Angular4 ngIf将为您提供更多细节。
希望这个龙胆会帮助你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.