angular2:为什么我们将 asterik 与 ngif 和 ngfor 一起使用?

zee*_*han 3 angular2-template

这是所提问题的示例代码。<p *ngIf="heroes.length >= 4">There are many heroes!</p> 如果我删除 * 它会给我错误

小智 5

来源:https ://angular.io/docs/ts/latest/guide/structural-directives.html#!#asterisk

星号 (*) 效果

复制代码

<div *ngIf="hero">{{hero}}</div>
<div *ngFor="let hero of heroes">{{hero}}</div>
Run Code Online (Sandbox Code Playgroud)

我们在这些指令名称前添加星号 (*)。

星号是“语法糖”。它为作者和读者简化了 ngIf 和 ngFor。在底层,Angular 用更详细的形式替换了星号版本。

接下来的两个 ngIf 示例实际上是相同的,我们可以用任一风格编写:

复制代码

<!-- Examples (A) and (B) are the same -->
<!-- (A) *ngIf paragraph -->
<p *ngIf="condition">
  Our heroes are true!
</p>

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

我们大多数人宁愿用风格(A)来写作。

值得注意的是,Angular 将样式 (A) 扩展为样式 (B)。它将段落及其内容移动到标签内。它将指令向上移动到标签,在那里它成为属性绑定,用方括号括起来。宿主组件的条件属性的布尔值决定是否显示模板化内容。