ng2 - ng-container和ng-template标签之间的区别

问题描述 投票:64回答:5

有人可以说明使用<ng-container><ng-template>元素之间的区别吗?

我找不到NgContainer的文档,也不太了解模板标签之间的区别。

每个代码示例都会有很大帮助。

angular
5个回答
79
投票

它们都是(2.x,4.x)用于将元素组合在一起而不必引入另一个将在页面上呈现的元素(例如divspan)。

然而,template需要讨厌的语法。例如,

<li *ngFor="let item of items; let i = index; trackBy: trackByFn">...</li>

会成为

<template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
  <li>...</li>
</template>

您可以使用ng-container,因为它遵循您期望的并且可能已经熟悉的漂亮的*语法。

<ng-container *ngFor="let item of items; let i = index; trackBy: trackByFn">
  <li>...</li>
</ng-container>

您可以通过阅读this discussion on GitHub找到更多详细信息。


请注意,在4.x中,<template>已弃用,并更改为<ng-template>


使用


9
投票

ng-template用于结构指令,如ng-ifng-forng-switch。如果您在没有结构指令的情况下使用它,则不会发生任何事情,它将呈现

当您没有合适的包装或父容器时,将使用ng-container。在大多数情况下,我们使用divspan作为容器,但在这种情况下,我们想要使用多个结构指令。但是我们不能在元素上使用多个结构指令,在这种情况下,ng-container可以用作容器


1
投票

顾名思义,ng-template表示模板。它本身并不呈现任何东西。我们可以使用ng-container提供占位符来动态呈现模板。

ng-template的另一个用例是我们可以使用它来将多个结构指令嵌套在一起。你可以在这篇博文中找到很好的例子:angular ng-template/ng-container


0
投票

简单来说,ng-container就像React的高级组件,它只能帮助渲染其子元素。

ng-template基本上用于Angular的内部实现,其中ng-template中的任何内容在渲染时都被完全忽略,它基本上成为对视图源的注释。这应该与Angular的内部指令一起使用,如ngIfngSwitch等。


0
投票

ng-template显示真值。

<ng-template>
    This is template block
</ng-template>

输出:

没有条件的ng-container show也显示内容。

<ng-container>
    This is container.
</ng-container>

输出: 这是容器。

© www.soinside.com 2019 - 2024. All rights reserved.