Lesson 9

Understanding Content Projection

Projecting supplied content inside of a custom component

PRO

Lesson Outline

Understanding Content Projection

An important concept in building custom components is content projection - it is similar in concept to providing a component with @Input except that it works a little differently. When we are using components in our templates, we may just use the component like this:

<my-component></my-component>

but often we place content between those tags like this:

<my-component>I'm some content!</my-component>

Content projection takes the content that we supply between the components tags, and projects it inside of the component's template. If the template of MyComponent looked like this:

<h2>My cool component!</h2>

then we would see the following output to the browser when we run the application:

My cool component!

There is no content projection happening here, all we would see is the normal template for the component. We don't see the I'm some content! we added between the <my-component> tags. However, if we add the <ng-content> tag to the template for the component:

<h2>My cool component!</h2>
<ng-content></ng-content>

the content we supply inside of the <my-component> tags:

<my-component> I'm some content! </my-component>

will be projected into the component's template wherever the <ng-content> tag is. This would cause the output to look like this:

My cool component!
I'm some content!

If we were to move the <ng-content> tag above the <h2> tag, then the I'm some content! would be displayed above the heading instead. Whatever we add inside of the components tags will be projected to wherever <ng-content> is. If there is no <ng-content> tag, then the content inside of the <my-component> tags would not be displayed.

PRO

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).