Angular 2 Transclusion with ng-content in one go

Transclusion was one of the coolest feature of Angular 1.
Angular 2 made this (way) more simple and also changed its name to Projection.
What we used to configure in our directives with some symbols and ngTransclude is now directly handled into the DOM.

Before diving into it, let’s refresh our memory.
Here is the most basic Projection example:


Projection transclusion Angular 2

We pass some content to a Projector Component and it will display it into the corresponding slot.

Here is the Projector Component:

Yes! There is basically nothing there, only the templateUrl where the work is done:

The ng-content Component will use the content placed between the <projector> </projector> tags, just like this:

The result:

Angular 2 Projected basic content

If we want to be more precise we can project by:

  • Class name
  • Element
  • Attribute

Here is how we pass the content:

The select attribute allows us to pick the content that we want to use for the slot, just like this:

The result:

Angular 2 Projected advanced content

As you can see even though we ordered differently in the first template, the order is dictated by the ng-content tags placement, so be careful there and enjoy your Projections!

Subscribe to my mailing list to get access to a Free 7-day Ionic 3 introduction email course!
100% Privacy. I'll never spam you!


No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *