为什么 *ngFor 不需要括号?

Why doesn't *ngFor need brackets?

我是Angular框架的新手,最近被介绍了属性*ngFor=""

据我了解,这采用与 JavaScript for() 循环相同的参数...因此,*ngFor="let item of itemCollection"。但是,与其他指令相比,*ngFor 不需要将其周围的 [] 视为代码。

This documentation page 表明 hero 属性需要 [] 围绕它,以便将值视为代码,并返回 "hero":[=23 的值=]

<app-hero-detail *ngFor="let hero of heroes" [hero]="hero"></app-hero-detail>

为什么会这样? *ngFor 也被评估,但不需要 [] 显然......是 * 前缀表示该值必须始终被视为代码还是什么?

括号 [x] 用于 属性 绑定,而 (x) 用于事件绑定。

虽然 *ngFor、*ngIf 是指令而不是绑定,但它们给出了这样的语法。

首先您必须了解括号符号 [] 用于 Angular 中的 property binding

我将使用您提供的示例代码来帮助解释这一点:

<app-hero-detail *ngFor="let hero of heroes" [hero]="hero"></app-hero-detail>

在这种情况下,[hero]="hero" 中的 [hero] 是 属性 绑定的示例,其中数据将从数据源(组件)one-way 流向查看(HTML)。您会发现 属性 hero 是使用 @Input decorator 在该组件的输入 属性 中定义的。

这让我们想到了您的问题:

Why doesn't *ngFor need brackets?

答案和你想的一样。由于星号 (*) 的存在,您不需要对 *ngFor 使用 [括号表示法]。星号是 Angular 速记符号(或语法糖),它允许开发人员编写更清晰、更易于理解和维护的代码。在表格下方,当 Angular 编译器 "desugars" 您的代码时,它会看起来像这样:

<template [ngFor]="let hero of heroes">
     <div></div>
 </template>

从那里 Angular 编译器将进一步 "desugar" 您的代码如下所示:

<template ngFor let-hero="$implicit" [ngForOf]="heros">
   <div>...</div>
 </template>

所以最后你可以看到 ngFor Structural Directive ultimately is treated like any other property that requires property binding. However, on account of it being a built in directive Angular provided us with a much cleaner to use shorthand notation. Unlike the hero property which we created and defined ourselves, therfore requiring us to use the bracket notation explicitly in the HTML. Don't forget even though you can use the bracket notation with structural directives you should always prefer the asterisk