Passing HTML into my component

Limnic picture Limnic · Feb 16, 2017 · Viewed 13k times · Source

Consider the following component sidebar.component.html:

<div class="sidebar">
  <ul>
    <li class="tooltipped" data-position="right" data-delay="50" data-tooltip="Go to the dashboard">
      <a href="#">
        <i class="material-icons">home</i>
        <span>Home</span>
      </a>
    </li>
    <li class="tooltipped" data-position="right" data-delay="50" data-tooltip="Manage your times">
      <a href="#">
        <i class="material-icons">watch_later</i>
        <span>Times</span>
      </a>
    </li>
    <li class="tooltipped" data-position="right" data-delay="50" data-tooltip="Go to settings">
      <a href="#">
        <i class="material-icons">settings</i>
      </a>
    </li>
  </ul>
</div>

In app.component.html, I use the sidebar using its tags (<sidebar>). However, now I want to make it so that the <li> elements are given inside the <sidebar> tags so that they are no longer inside sidebar.component.html to make the component re-usable.

I'm not sure what this is called and I am having trouble finding it.

Thanks in advance.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Feb 16, 2017

Create a sidebar component with an <ng-content> where the passed children should be displayed

@Component({
  selector: 'sidebar',
  template: '<ul><ng-content></ng-content></ul>'
})
export class SidebarComponent {
}

and use it like

<sidebar>
    <li class="tooltipped" data-position="right" data-delay="50" data-tooltip="Go to the dashboard">
      <a href="#">
        <i class="material-icons">home</i>
        <span>Home</span>
      </a>
    </li>
    <li class="tooltipped" data-position="right" data-delay="50" data-tooltip="Manage your times">
      <a href="#">
        <i class="material-icons">watch_later</i>
        <span>Times</span>
      </a>
    </li>
    <li class="tooltipped" data-position="right" data-delay="50" data-tooltip="Go to settings">
      <a href="#">
        <i class="material-icons">settings</i>
      </a>
    </li>
</sidebar>