I noticed while using Angular, AngularJS and lately React that each have their own way of adding or customizing content within the component, enabling reuse and extendibility, in a series of blogs I want to explore how this is done using AngularJS, Angular and React.
"In computer science, transclusion is the inclusion of part or all of an electronic document into one or more other documents by reference via hypertext. Transclusion is usually performed when the referencing document is displayed, and is normally automatic and transparent to the end user.[1] The result of transclusion is a single integrated document made of parts assembled dynamically from separate sources, possibly stored on different computers in disparate places."https://en.wikipedia.org/wiki/Transclusion
ngTransclude with AngularJS
The following example has been taken from my Plunker. A basic stripped down directive that just shows how the ng-transclude is added to create a content slot that can be customised for each implementation of the directive/component
Creation of directive
I have created a directive called 'transcludeExample', the case is important both in the template and the directive name.
From the directive I have returned an object with the following.
- restrict: 'E' - Element directive (
<transclude-example>) - transclude: true
- template: - The HTML template or path to the HTML file
The HTML template should contain an element with an ng-transclude attribute directive, this acts a slot for the transcluded content.
Adding directive to the template
As the directive has restrict: 'E', this should be added as an element
<transclude-example>…</transclude-example>
Any element added between these two tags will now be added into the directive/component.
Resulting in the page rendered below.
Conclusion
Transclusion is a useful technique in software development allowing you to reuse your component with a section that can be populated with different content.
Cover photo by wbd on Freeimages.com