Difference between ng-template, ng-container and ng-content
1: <ng-template></ng-template>
As the name suggests the <ng-template> is a template element that Angular uses with structural directives ( *ngIf , *ngFor , [ngSwitch] and custom directives). These template elements only work in the presence of structural directives, which help us to define a template that doesn’t render anything by itself, but conditionally renders them to the DOM. It helps us create dynamic templates that can be customized and configured.
Is it possible to use two structural directives together in one single element?
No, if we try to do so, we will get the error “Uncaught Error: Template parse errors: Can’t have multiple template bindings on one element.”
So instead of doing this:
We may need to introduce an additional wrapper component, however, this can be avoided by using ng-container:
2) <ng-container></ng-container>
ng-container is an extremely simple directive that allows you to group elements in a template that doesn’t interfere with styles or layout because Angular doesn’t put it in the DOM
This is helpful if you don’t want any extra div on DOM, you can simply use ng-container.
The advantage here is that we no longer need any additional wrapper(div) elements.
3) <ng-content></ng-content>
ng-content is used to project content into Angular components. You use the <ng-content></ng-content> tag as a placeholder for that dynamic content, then when the template is parsed Angular will replace that placeholder tag with your content.
If you check on your browser <div>Child Component Details</div> inside
<app-child></app-child> would not be visible. What if we want to show this content?
So this is where the ng-content directive comes into the picture. What we need to do is, just add “ng-content” inside the component template and it will find the content inside the directive tag and add it to that template at that particular place where we added the “ng-content” tag.
Reference: https://vibhas1892.medium.com, https://www.educative.io/
0 comments:
Post a Comment