How can I understand when to use ng-template
versus a Component in Angular?
Say I want to display a UI and I'll use it within the same component at several places. Should I create a template or a separate component?
<ul>
<li> ... </li>
<li> ...</li>
</ul>
An issue I am facing is that I have the above UI which I want to use at several places within a component. However, I want to give a unique id to each ul
and also set attributes of li
. I thought of using ng-template
but I am unable to figure out how to access ul
and li
once the template is inserted using createEmbeddedView
.
See this demo - https://stackblitz.com/edit/angular-bqm11b
My Component's HTML looks like
<ng-template #tmpl>
<ul>
<li> ... </li>
<li> ...</li>
</ul>
</ng-template>
I have created two ng-container
s
<ng-container #vc1></ng-container>
<ng-container #vc2></ng-container>
I am inserting #tmpl
in vc1
and vc2
but the final HTML looks like
<ul>
<li> ... </li>
<li> ...</li>
</ul>
<ul>
<li> ... </li>
<li> ...</li>
</ul>
I reckon that if I use a Component, I can set id and other attributes but if I use a template, I cannot do so because I cannot access ul
and li
and distinguish between the different ul
and li
. I don't want to mix pure JS
in my code so I want a solution which is more Angular (ViewChild
, ContentChild
, Rendere2
).
Am I correct that:
- In template, I cannot access
ul
andli
and distinguish between the differentul
andli
. - I should use template if I want vanilla UI but if I want to manipulate DOM then it is better to use a separate component?