Wanna keep up to date with the latest webdev stuff? Follow me on Twitter

My friend Todd knows how to create top-notch video courses. Check out Ultimate Angular!

What's this?

If you’re an AngularJS developer, I’m sure you heard about transclusion. Sounds really weird and mysterious, at least that’s what I thought when I first heard it.

If you google for it, you’ll probably land on one of Thoughtram’s articles (as you’ll do 90% of the time if you search for Angular articles :wink:). This one is about multiple transclusion and named slots which is available in Angular 1.5.
What it does is to allow you to basically specify multiple regions within your component’s template, which can be provided by the component user. This is a huge improvement as previously you had to do a couple of hacks to arrive to the same result.

But what about Angular version 2+, I thought, and so I tweeted:

And here we go.

//our root app component
import {Component} from '@angular/core'

  selector: 'multi-content',
  template: `
    <h3>Demoing content projection</h3>
    <div class="box">
      <ng-content select="[header]"></ng-content>
    <div class="box">
      <ng-content select="[body]"></ng-content>
  styles: [
    .box {
      min-height: 30px;
      border: 1px solid black;
      display: block;
export class ContentProjectionComponent {}

We use <ng-content> alone if we don’t have the need for multiple content projection (as it’s apparently called in Angular). Otherwise, we can use the select property:

<ng-content select="[header]"></ng-content>

The component user can then define which content goes where:

    <div header>This is projected to the header region</div>
    <div body>This goes to the body instead</div>

Try it out yourself:

Important Note!

Currently there is an issue if you try to project some content that is controlled by one of the *-prefixed directives like *ngIf, *ngFor etc. As such, using our example above in the following way:

  <span header>This is projected to the header region</span>
  <div body *ngIf="isVisible">
    This goes to the body instead.

..wouldn’t work, more specifically, the body region wouldn’t be projected. See issue 6303 for more details on this.

If you enjoyed this post you might want to follow me on Twitter for more news around JavaScript and Angular or watch my Egghead.io video lessons. :smiley: