ng-if和*ng-if在angular2中有什么区别

She*_*ero 23 javascript angular-ng-if angular

我试图理解ng-if和*ng-if之间的区别,但它们看起来和我一样.

是否存在差异,我应该记住选择一个而不是何时使用这些指令?

Thi*_*ier 31

ngIf是指令.因为它是结构指令(基于模板),所以您需要使用*前缀将其用于模板.

*ngIf 对应于以下语法的快捷方式("syntactic sugar"):

<template [ngIf]="condition">
  <p>
    Our heroes are true!
  </p>
</template>
Run Code Online (Sandbox Code Playgroud)

相当于:

<p *ngIf="condition">
  Our heroes are true!
</p>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此文档:


Gün*_*uer 9

不同的是Angular2中不支持两者;-)至少在当前版本中 - 它应该是*ngIf或ngIf.

结构指令可以与显式<template>标记或隐式<template>标记一起使用.对于隐式版本*,需要指示它是结构指令.

明确的

<template [ngIf]="someExpr">
   <div>content</div>
</template>
Run Code Online (Sandbox Code Playgroud)

或者从2.0.0首选

<ng-container *ngIf="someExpr">
   <div>content</div>
</ng-container>
Run Code Online (Sandbox Code Playgroud)

含蓄

<div *ngIf="someExpr"></div>
Run Code Online (Sandbox Code Playgroud)

通常您将使用隐式版本,因为它更简洁.

何时使用显式版本?

存在隐式版本不起作用的用例.

  • 如果你想要一个像申请不止一个结构指令ngFor 和 ngIf不被支持,那么你可以使用显式的形式,其中之一.

而不是这种无效的语法

<div *ngFor="let item of items" *ngIf="!item.hidden"></div>
Run Code Online (Sandbox Code Playgroud)

您可以使用

<ng-container *ngFor="let item of items">
  <div *ngIf="!itemHidden></div>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
  • 如果要将结构指令应用于多个元素

例如,您想要列出几行name和price每行

<tr>
  <td *ngFor="???">item.name</td>
  <td>item.price</td>
</tr>

<tr>
  <ng-container *ngFor="let item of items">
    <td>item.name</td>
    <td>item.price</td>
  </ng-container>
</tr>
Run Code Online (Sandbox Code Playgroud)


小智 5

为了简单起见,在迄今为止最新的 Angular 版本中,例如当我们使用 *ngIf 时,如下所示。

<div *ngIf = "condition">
//code here
</div>
Run Code Online (Sandbox Code Playgroud)

现在,上面的代码实际上是通过 Angular 渲染的,如下所示:

<ng-template [ngIf]="condition">
<div>
//code here
</div>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

因此,我们可以直接使用 *ngIf 作为结构指令,也可以使用 [ngIf] 作为属性指令,但使用 ng-template。希望这能让事情变得更加清晰。