Most (well maintained) Angular projects eventually reach the point where they would benefit from having a few generic components that use transclusion.
Maybe you have a timeline feed screen with multiple types of feed items.
Or some tabs widget.
Or a generic modal you use across the app.
Transclusion allows us to create very customizable components since you can inject them with other components, and not just pass rigid inputs (e.g. specific bindings). That’s pretty much how things like ng-repeat work: you provide those directives with inner HTML that they then use.
Prior to Angular 1.5 a component could only transclude a single entry: whatever you gave it was had to be used as a whole.
But, among other goodies introduced in 1.5 we also got multiple slot transclusion, which comes in handy at times.
Say you want to create a generic modal, that can have both the title and body customized.
Here’s an example of someone using the
modal component we’ll create:
1 2 3 4 5 6
modal-body elements are the transclusion slots we will now define and use in our
1 2 3 4 5 6 7 8 9 10 11 12 13
As you can see above, we define the component’s
transclude property to have 2 slots, named
Each slot also has the name of the element it expects to see its content inside.
Then in the component’s template we can decide where to insert the transcluded elements by using the
ng-transclude directive and supplying it with the slot’s name.
As you can see transclusion automatically takes care of things like passing the scopes correctly so that even though the templates we passed reference the original component’s scope (
$ctrl), it’s still properly visible inside.
“Maintaining AngularJS feels like Cobol 🤷…”
You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?
It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.
Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.