Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Nesting Elements in Angular 2 Components with ng-content (AKA Angular 2 Transclusion)

    2 - 6

    You can place content inside of the instance of your component element then manage it inside of the component’s template using ng-content. This process is called reprojection, but you may be more familiar with the term “transclusion”.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Inside our Home component, let's delete a couple of lines, so it's one widget with that one message. Let's comment that out for a second and bring back that old trusty Widget 2 with just the 2 in there.

    Now, if we want to pass some content into Widget 2, say "Stuff goes here!" Then inside of Widget 2, instead of div, you actually put ng-content. That ng-content is going to take everything that you put inside of Widget 2 and drop it inside of the widget template.

    If I hit Save, this ng-content is replaced with "Stuff goes here!" Now, you can even do that with things like, let's bring back, Widget 1. I'll cut this. Paste that inside of Widget 2. Hit save, and now we have Widget 1 inside of Widget 2. Add styles and do the host thing we just learned about, the display of block, and a border of three pixel solid red.

    You can see here, we'll now have a red border around the black dash border showing that this Widget 2 now has Widget 1 inside of it. These components are working together inside of the home component where one is taking in data using the input method and that's Widget 1.

    Widget 2 is taking in this element, and then inside of there, it's placing the element inside the template. I could say above, below and you'll see that it's really placing it inside of this template. Above, below and then ng-content which is, for all intents and purposes, our Widget 1.

    Then back at home, you could even create another Widget 2 with some other content. Hit Save. You'll see two Widget 2s, one with the Widget 1 content and the second one with the other content. That's done using the ng-content tag.