带 else 块的 *ngIf 指令中的分号 - Angular

Semicolon in *ngIf directive with else block - Angular

最近我在 Angular 中使用了一个 *ngIf 指令 和一个 else 块 并且想知道为什么在 Angular docs 中的例子使用了一个分号(<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>),因为这似乎也可以在没有分号的情况下工作。

不使用分号有什么副作用吗?或者这只是一种更简洁的编码方式?

只有在使用 "else" 块时才需要分号。 所以, <div *ngIf="condition">(不带分号)是不使用 'else' 时的规范形式,但 <div *ngIf="condition;">(带分号)也是有效的, 使用 'else'.

时,<div *ngIf="condition; else elseBlock"> 是必需的形式

在仔细查看 documentation.

之前,我还不知道其他一些有趣的语法选项

先见之明

回想起来,这是一个很有趣的问题。实际问题是 <div *ngIf="condition; else elseBlock"> 按预期工作。但 <div *ngIf="condition else elseBlock"> 也是如此,那有什么用呢?分号的实际需要是什么?

说明

原来是Angularmicrosyntax specification that defines how *ngIf is expanded to [ngIf] is quite flexible and difficult to grasp initially. The official Angular docs doesn't go in-depth. A good explanation could be found here and here。解释的要点是微语法定义的形式是

*:prefix="( :let | :expression ) (';' | ',')? ( :let | :as | :keyExp )*"

  • :prefix: HTML attribute key.
  • :key: HTML attribute key.
  • :local: local variable name used in the template.
  • :export: value exported by the directive under a given name.
  • :experession: standard angular expression
  • :keyExp = :key ":"? :expression ("as" :local)? ";"?
  • :let = "let" :local "=" :export ";"?
  • :as = :export "as" :local ";"?

看来分号是可选的。此外,在我们的例子中,else 块是一个关键表达式,可以看出冒号是可选的,我们目前没有使用。所以理论上我们也可以使用 <div *ngIf="condition else: elseBlock">。因此, ngFor 也可以不带任何分号使用。所以下面的块也可以工作

<div *ngFor="let n of arr let i=index let f=first let l=last">
  {{ n }}
</div>

工作示例:Stackblitz