In AngularJS, transclusion allows us to preserve and display the original content inside a directive. It is achieved using ng-transclude
.
By default, when a directive replaces an element, it removes the original content inside that element.
With transclusion, the directive keeps and reuses that content.
1. Why Use Transclusion?
✔ Keeps the original content inside the directive.
✔ Helps in creating flexible and reusable UI components.
✔ Allows wrapping elements without losing content.
2. Basic Example of Transclusion (ng-transclude
)
Directive Code (JavaScript)
var app = angular.module("myApp", []);
app.directive("customBox", function () {
return {
restrict: "E",
transclude: true, // Enable transclusion
template: `
<div style="border: 2px solid blue; padding: 10px;">
<h3>Custom Box</h3>
<div ng-transclude></div> <!-- Content will appear here -->
</div>
`
};
});
HTML Usage
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">
<custom-box>
<p>This is inside the custom directive.</p>
</custom-box>
</body>
</html>
Output:
The content inside <custom-box>
(<p>...</p>
) will be preserved inside the directive.
3. How It Works?
- The directive replaces
<custom-box>
with its template. ng-transclude
ensures the<p>
inside<custom-box>
remains.- Without
ng-transclude
, the<p>
would be lost.
4. Transcluding Multiple Sections
We can use named transclusion to place content in different sections.
Directive Code (JavaScript)
app.directive("customCard", function () {
return {
restrict: "E",
transclude: {
headerSlot: "header",
contentSlot: "div"
},
template: `
<div style="border: 2px solid green; padding: 10px;">
<h3 ng-transclude="headerSlot"></h3>
<p ng-transclude="contentSlot"></p>
</div>
`
};
});
HTML Usage
<custom-card>
<header>Card Title</header>
<div>Card Content Goes Here</div>
</custom-card>
Output:
“Card Title” appears in <h3>
.
“Card Content Goes Here” appears in <p>
.