Angular 为什么要使用ng模板而不是*ngIf

Angular 为什么要使用ng模板而不是*ngIf,angular,Angular,使用的任何理由: <div *ngIf="show; else notShow">content</div> <ng-template #notShow>other content...</ng-template> 内容 其他内容。。。 而不是: <div *ngIf="show">content</div> <div *ngIf="!show">other content...</div> 内

使用的任何理由:

<div *ngIf="show; else notShow">content</div>
<ng-template #notShow>other content...</ng-template>
内容
其他内容。。。
而不是:

<div *ngIf="show">content</div>
<div *ngIf="!show">other content...</div>
内容
其他内容。。。

Angular将宿主元素(应用了该指令)包装在
内部,并通过使用诊断注释替换完成的DOM中的

1.
内容

上面的代码段将在DOM中转换为下面的代码段

<ng-template [ngIf]="show">
  <div>content</div>
</ng-template>

内容
Angular将
替换为诊断注释

因此,如果你检查它,它会像:

<!--bindings={
 "ng-reflect-ng-if":"true"
}-->
<div>content</div>

内容

2.
内容

这将被视为:

<ng-template [ngIf]="show">
  <ng-template>content</ng-template>
</ng-template>

内容
在DOM中,它将是

<!--bindings={
 "ng-reflect-ng-if":"true"
}-->
<!---->


对于代码的第一个片段

<div *ngIf="show; else notShow">content</div>
<ng-template #notShow>other content...</ng-template>
内容
其他内容。。。
这就是它在DOM中的呈现方式

第二段

<div *ngIf="show">content</div>
<div *ngIf="!show">other content...</div>
内容
其他内容。。。
这就是它在DOM中的呈现方式



请通读这篇文章,它对你的问题有一个清楚的解释

这纯粹是语义学。这两个示例之间没有性能优势。所以你用哪一个都没关系。这里的关键区别在于else语法是过程性的。您可以引用名为
notShow
的组件属性,该属性是您在运行时创建的模板。您只是使用速记参考
#notShow
在当前模板中使用

以下是
*ngIf
的源代码:

private _updateView() {
  if (this._context.$implicit) {
    if (!this._thenViewRef) {
      this._viewContainer.clear();
      this._elseViewRef = null;
      if (this._thenTemplateRef) {
        this._thenViewRef =
            this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
      }
    }
  } else {
    if (!this._elseViewRef) {
      this._viewContainer.clear();
      this._thenViewRef = null;
      if (this._elseTemplateRef) {
        this._elseViewRef =
            this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
      }
    }
  }
}
this.\u context.$implicit
是模板中的条件表达式


在任何一种情况下,都会调用
this.\u viewContainer.clear()
。因此,我在您的示例中看不到性能差异。

如果
ngIf
条件更复杂,您可能更喜欢第一个版本。我可以想象,通常使用“else”语句的原因也是一样的。如果它们没有用处,它们就不存在了。有些人喜欢将它们的
放在模板文件的底部或顶部。这可以使HTML更易于阅读,因为then/else内容不会给显示业务逻辑的模板增加噪音<代码>只是更小,模板可以在HTML文件的其他地方。回答不错。我不知道结构化指令被重写成了
。显然是的,我最近也发现了:)