简体   繁体   中英

Benefit of using ng-container vs. template?

In angular we could do:

template: `<ng-container #c></ng-container>`

or:

template: `<template #c></template>`

To create a view container that is hidden when the template is rendered.

Is there a difference between using ng-container over the html template alternative? I'm guessing Angular has to have it's own template containers like ng-template or ng-container since use of the raw html template element could break non browser based runtimes, like mobile clients, etc.

The <ng-container> is always rendered, but does not represent a DOM element. It is still attached to the component's view.

The <ng-template> will only be rendered if it is explicitly requested.

Here's a good reference on the subject:

http://nataliesmith.ca/blog/2018-05-01-ngtemplate-ngcontainer-ngcontent/

To create a view container that is hidden when the template is rendered.

Always use <ng-template> when possible. The <ng-container> is for grouping DOM elements together. For example; when you need to apply a *ngIf to many <td> elements, because you can not use a <span> around <td> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM