Understanding Content Projection
Projecting supplied content inside of a custom component
PROModule Outline
- Source Code & Resources PRO
- Lesson 1: Introduction PUBLIC
- Lesson 2: The Role of Components and Directives PUBLIC
- Lesson 3: When to Use Custom Components & Directives PRO
- Lesson 4: Building a Simple Component PRO
- Lesson 5: Building a Simple Directive PRO
- Lesson 6: Setting up Components and Directives PRO
- Lesson 7: Using @Input and @Output PRO
- Lesson 8: Using ElementRef and Renderer PRO
- Lesson 9: Understanding Content Projection PRO
- Lesson 10: Understanding @ViewChild and @ContentChild PRO
- Lesson 11: Building a Complex Component PRO
- Lesson 12: Listening for Events and Binding to Properties PRO
- Lesson 13: Building a Skeleton Card Component PRO
- Lesson 14: Creating an Autogrow Directive for a Textarea PRO
- Lesson 15: Handling Error Messages with a Custom Component PRO
- Lesson 16: Building a Parallax Header Directive PRO
- Lesson 17: High Performance Accordion Component PRO
- Lesson 18: Conclusion 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.
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).