What's exactly transclusion in Angular. I found some information about it in AngularJS but how it's working in Angular. When to use it in practise and in which cases?
-
1A search on google will take you to multiple articles that provide detailed information on it. – Wand Maker Feb 09 '20 at 18:20
1 Answers
Transclusion is a concept that let's you create a content-slot / ng-content inside your component. So if you have a child component with a content-slot / ng-content, the parent component that uses the child component can put whatever it wants inside the content-slot of the child component.
Imagine you have two components like this:
Child Component
<div>Child start</div>
<ng-content></ng-content>
<div>Child end</div>
Parent Component
<div>Parent start</div>
<app-child>
<div>Parent middle</div>
</app-child>
<div>Parent end</div>
On the screen it will render something like this:
Parent start
Child start
Parent middle
Child end
Parent end
As you can see the line "Parent middle" is rendered in the middle of the child. This can be a very powerful concept that let's you create reusable children that can have content decided by their parent.
If you have ever used the Angular Material Card component, it is a prime example of this. The card component creates the card borders and set's the background to white, but the developer can from the parent component decide whatever is to be inside the card.
Also worth mentioning is that you can have several contents-slots / ng-content in a single component, and you can assign them an id. By referencing the ID you can from the parent decide what goes where inside the child component.

- 2,740
- 1
- 14
- 17