问题描述
有人可以说明使用<ng-container>
和<ng-template>
元素之间的区别吗?
Can someone please illustrate the difference between using <ng-container>
and <ng-template>
elements?
我找不到NgContainer
的文档,也不太了解模板标记之间的区别.
I could not find documentation for NgContainer
and don't quite understand the difference between template tag.
每个代码示例都会有很大帮助.
A code example of each would greatly help.
推荐答案
目前,这两种方法(2.x,4.x)都用于将元素分组在一起,而不必引入将在界面上呈现的其他元素.页面(例如div
或span
).
Both of them are at the moment (2.x, 4.x) used to group elements together without having to introduce another element which will be rendered on the page (such as div
or span
).
template
需要讨厌的语法.例如,
template
, however, requires nasty syntax. For example,
<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
代替,因为它遵循了您期望的并且可能已经很熟悉的漂亮的*
语法.
You can use ng-container
instead since it follow the nice *
syntax which you expect and are probably already familiar with.
<ng-container *ngFor="let item of items; let i = index; trackBy: trackByFn">
<li>...</li>
</ng-container>
您可以通过阅读在GitHub上进行的讨论来找到更多详细信息.
请注意,在4.x版本中,<template>
已弃用,并更改为<ng-template>
.
Note that in 4.x <template>
is deprecated and is changed to <ng-template>
.
使用
-
<ng-container>
,如果您需要诸如*ngIf
或*ngFor
或如果您想在这样的结构指令中包装多个元素; -
<ng-template>
如果需要使用ngForTemplate
在各个位置标记的视图摘录",请ngTemplateOutlet
或createEmbeddedView()
.
<ng-container>
if you need a helper element for nested structural directives like*ngIf
or*ngFor
or if you want to wrap more than one element inside such a structural directive;<ng-template>
if you need a view "snippet" that you want to stamp at various places usingngForTemplate
,ngTemplateOutlet
, orcreateEmbeddedView()
.
这篇关于ng2-ng容器标签和ng-template标签之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!