![]() |
VOOZH | about |
Both ng-container and ng-template can be used to create responsive and dynamic components. Angular provides a set of structural directives that can be used with both ng-template and ng-container such as:
These structural directives are used to alter the structure of the DOM by conditionally rendering the HTML elements.
Both ng-container and ng-template render the wrapped elements while hiding themselves but they both follow different mechanisms, these difference will be shown in the following article.
ng-template: Let's try an example:
Yes, nothing will be rendered. When we check the HTML code, we will see:
👁 ImageIt is because ng-template does not do anything on its own. It needs some rendering logic to render something.
Let's try another example:
This time output will be like this:
👁 ImageIn both the example, we can see template comments itself out, rendering the wrapped content conditionally.
ng-container: The 'ng-container' indeed shares some similarities with 'ng-template', like they both render the wrapped content while omitting themselves. But ng-container, on the other hand, is used when we use multiple structural directives and have no suitable parent wrapper. It does not require a structural directive to render the child elements unlike ng-template were using a structural directive was necessary.
Let's see an example:
Now in this case, HTML was rendered even without any structural directive:
👁 ImageLet's see what will happen if we wrap a ng-template inside a ng-container:
ng-container successfully wraps a ng-template:
👁 ImageTo conclude, we can say that both the ng-container and ng-template are used to wrap HTML elements. They differ in their mechanisms. Also, multiple structural directives are not possible inside ng-template but ng-container can be used to wrap multiple elements containing different structural directives so it is a perfect container.