title: When to use a Template vs Component in Angular?
body: <p>How can I understand when to use <code>ng-template</code> versus a Component in Angular? </p>
  
  <p>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?</p>
  
  <pre><code>&lt;ul&gt;
  &lt;li&gt; ... &lt;/li&gt;
  &lt;li&gt; ...&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>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 <code>ul</code> and also set attributes of <code>li</code>. I thought of using <code>ng-template</code> but I am unable to figure out how to access <code>ul</code> and <code>li</code> once the template is inserted using <code>createEmbeddedView</code>.</p>
  
  <p>See this demo - <a href="https://stackblitz.com/edit/angular-bqm11b" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-bqm11b</a></p>
  
  <p>My Component's HTML looks like</p>
  
  <pre><code>&lt;ng-template #tmpl&gt;
      &lt;ul&gt;
      &lt;li&gt; ... &lt;/li&gt;
      &lt;li&gt; ...&lt;/li&gt;
      &lt;/ul&gt;
  &lt;/ng-template&gt;
  </code></pre>
  
  <p>I have created two <code>ng-container</code>s </p>
  
  <pre><code>&lt;ng-container #vc1&gt;&lt;/ng-container&gt;
  &lt;ng-container #vc2&gt;&lt;/ng-container&gt;
  </code></pre>
  
  <p>I am inserting <code>#tmpl</code> in <code>vc1</code> and <code>vc2</code> but the final HTML looks like</p>
  
  <pre><code>&lt;ul&gt;
  &lt;li&gt; ... &lt;/li&gt;
  &lt;li&gt; ...&lt;/li&gt;
  &lt;/ul&gt;
  &lt;ul&gt;
  &lt;li&gt; ... &lt;/li&gt;
  &lt;li&gt; ...&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>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 <code>ul</code> and <code>li</code> and distinguish between the different <code>ul</code> and <code>li</code>. I don't want to mix pure <code>JS</code> in my code so I want a solution which is more Angular (<code>ViewChild</code>, <code>ContentChild</code>, <code>Rendere2</code>).</p>
  
  <p>Am I correct that:</p>
  
  <ol>
  <li>In template, I cannot access <code>ul</code> and <code>li</code> and distinguish between the different <code>ul</code> and <code>li</code>. </li>
  <li>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?</li>
  </ol>