ng2-ng容器标签和ng-template标签之间的区别 [英] ng2 - Difference between ng-container and ng-template tags

查看:77
本文介绍了ng2-ng容器标签和ng-template标签之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以说明使用<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)都用于将元素分组在一起,而不必引入将在界面上呈现的其他元素.页面(例如divspan).

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在各个位置标记的视图摘录",请 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 using ngForTemplate, ngTemplateOutlet, or createEmbeddedView().

这篇关于ng2-ng容器标签和ng-template标签之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆