2

我正在尝试找出 Angular2 结构指令,目前,我无法发现 conditionaldiv和 conditional之间的区别ng-template

从技术上讲,这段代码:

  <div *ngIf="true">
    <other-component></other-component>
  </div>

将使用此代码执行相同的工作:

  <ng-template [ngIf]="true">
    <other-component></other-component>
  </ng-template>

根据官方文档:“*星号是更复杂的东西的“语法糖”。在内部,Angular 将ngIf 属性转换为一个<ng-template>元素,包裹在宿主元素周围。

Also, according to Angular University Blog : "Angular is already using ng-template under the hood in many of the structural directives that we use all the time: ngIf, ngFor and ngSwitch." (following the documentation above)

So, when it comes to write the statement in html, in simple words which is one is the proper one to render content conditionally and why. Any help is welcome!

4

2 回答 2

3

简单的答案是如果您可以使用 完成任务ngIfngFor或者ngSwitch不需要使用 ng-template 并使代码过于复杂。但是如果你需要像if elseAngular 这样的语句,最常见的方法是使用ng-template. 像这儿:

<div class="lessons-list" *ngIf="lessons else loading">
  ... 
</div>

<ng-template #loading>
    <div>Loading...</div>
</ng-template>
于 2018-07-16T08:37:29.567 回答
0

基于角度文档。

星号是更复杂的东西的“语法糖”。在内部,Angular 将 *ngIf 属性转换为一个元素,包裹在宿主元素周围,就像这样。

<ng-template [ngIf]="hero">
  <div class="name">{{hero.name}}</div>
</ng-template>

*ngIf 指令移动到它成为属性绑定的元素,[ngIf]。的其余部分,包括其类属性,在元素内移动。

在这里阅读更多

于 2018-07-16T08:31:42.700 回答