Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 746
Ole Avatar asked Jan 03 '19 20:01

Ole


People also ask

Why do we use ng-container?

ng-container allows us to create a division or section in a template without introducing a new HTML element. The ng-container does not render in the DOM, but content inside it is rendered. ng-container is not a directive, component, class, or interface, but just a syntax element.

What is the purpose of ng-template?

ng-template is an Angular element that is used for rendering HTML in a template. However, it is not rendered directly on DOM. If you include an ng-template tag to a template, the tag and the content inside it will be replaced by comment upon render.

What is the use of ng-template in Angular 6?

One of the main uses for <ng-template> is to hold template content that will be used by Structural directives. Those directives can add and remove copies of the template content based on their own logic. When using the structural directive shorthand, Angular creates an <ng-template> element behind the scenes.

Can we pass data to ng-template?

Passing data to ngTemplateOutletWe can also pass data to the using its second property ngTemplateOutletContext . Alternatively you can also use the following syntax. Pass more than one value.


1 Answers

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>.

like image 193
Reactgular Avatar answered Sep 28 '22 19:09

Reactgular