Angular: Creating Reusable Components

Mar 14, 2023
Angular

In this article, we’re going to demonstrate using content projection and the ng-content element to create a reusable toolbar Angular component.

The goal is to create a toolbar that looks like the image below where:

  • the title and links are provided to the toolbar as child elements in the component’s content.
  • the toolbar is responsible for positioning the content in this case the title and links.

Reusable Toolbar

Check out the full example on GitHub: https://github.com/minibuildsio/ng-content-example.

Using ng-content to Place Content in the Toolbar

In the HTML for the toolbar component, we use ng-content to place the content. We’re expecting two different types of content the title and the links, to differentiate between the content we can use the select property. For example, select="[title]" will place the content marked as the title in that slot any unmarked content will be placed in the ng-content slot without a select property.

<div class="toolbar">
  <ng-content select="[title]"></ng-content>
  
  <div class="full-width"></div>

  <div style="display: flex; gap: 12px">
    <ng-content></ng-content>
  </div>
</div>

Using the Reusable Toolbar

To use the toolbar we simply need to add an element to app-toolbar marked as the title e.g. <p title>...</p> and any further elements to be placed in the links select e.g. some anchor elements.

<app-toolbar>
  <p title>The Title</p>

  <a href="https://www.minibuilds.io/posts/angular-content-projection/">Article</a>
  <a href="https://www.minibuilds.io/">Minibuilds</a>
</app-toolbar>