Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

angular - ng2 - Difference between ng-container and ng-template tags

Can someone please illustrate the difference between using <ng-container> and <ng-template> elements?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, however, requires nasty syntax. For example,

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

would become

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

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>

You can find more details by reading this discussion on GitHub.


Note that in 4.x <template> is deprecated and is changed to <ng-template>.


Use

  • <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().

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...