Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating a Container Component in Angular 2 [Code Snippet]

DZone's Guide to

Creating a Container Component in Angular 2 [Code Snippet]

Juergen Gutsch needed a shared reusable component which turned out to be easier than expected. Check out these two code snippets that might just help you too.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

Creating such components was easier than expected. I anyway spent almost a whole day to find that solution, I played around with view and template providers, tried to access the template and to manipulate the template. I also tried to create an own structural directive.

But you just need to use the directive in the container component.

<nav>
  <div class="navigation pull-left">
    <ul>
      <!-- the menu items --->
    </ul>
  </div>
  <div class="pull-right">
    <ng-content></ng-content>
  </div>
</nav

That's all. You don't need to write any TypeScript code to get this working. Using this component is now pretty intuitive:

<div class="nav-bar">
  <app-navigation>
    <button (click)="printDraft($event)">print draft</button>
    <button (click)="openPreview($event)">Show preview</button>
  </app-navigation>
</div>

The contents of the - the buttons - will now be placed to the placeholder.

After spending almost a whole day to get this working my first question was: Is it really that easy? Yes, it is. That's all.

Maybe you knew about it. But I wasn't able to find any hint in the docs, on StackOverflow or in any Blog about it. Maybe this requirement isn't used needed often. At least I stumbled upon a documentation where ng-content as used and I decided to write about it. Hope it will help someone else.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
typescript ,angular 2 ,web dev ,code snippet

Published at DZone with permission of Juergen Gutsch, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}