Content Projection in Angular
Table of contents
No headings in the article.
Content projection - It is a pattern in which we may require to send/insert / project data dynamically to our angular components.
Is done using Ng-Content.
For Reusable / Scalable components
A slot can be thought of as a container or div.
Multislot => Multiple sets of data.
Conditional slot => Based on certain conditions, data will be rendered.
Content (Data) is sent from one component to another, which doesn't mean parent-child relationship always, content can be shared otherwise too!
If ng-content is removed then the content won't be projected no matter what you send from the calling component.
Here, in the <app-component>, we're trying to call another component, which is <app-content-projection> in our case & passing some content within. This content won't be rendered otherwise if we're not using ng-content.
View of <app-child-component> -
If there is no select attribute mentioned then, default content would be projected otherwise selectors would be matched for multiple containers/content to be rendered accordingly.
In the inspector, you can see the< ng-content> and the selector being rendered.
Conditional slot -
1. app-component - We define our content in the ng-template to be projected in the content-projection component.
2. capture the projected content in the content-projection component.
3. Display the projected content in the view. ngIf can be removed but is used only to represent the conditional flow.
Wanna see the full code in action?
Checkout my git repo for the same -