Hello guys how are you? Welcome back on my blog Therichpost. Today in this post I am going to share How to use ngTemplateOutlet in Angular to easily create dynamic components and share dependencies?
Angular 19 came. If you are new then you must check below two links:
Now guys here is the complete code snippet and please follow carefully:
The ngTemplateOutlet
directive in Angular is a powerful tool for dynamically rendering templates. It allows you to create reusable components or layouts, pass data or dependencies, and reduce redundancy in your codebase.
Here’s a detailed guide on how to use ngTemplateOutlet
effectively:
1. Understanding ngTemplateOutlet
The ngTemplateOutlet
directive binds a TemplateRef
(a reference to a template) to a container, rendering the content of the template dynamically. You can pass:
- A reference to a
ng-template
. - Context data to the template for dynamic customization.
2. Basic Usage
Here’s an example to demonstrate its usage:
<ng-container *ngTemplateOutlet="template"></ng-container> <ng-template #template> <p>This is a dynamic template!</p> </ng-template>
3. Passing Context to the Template
You can pass data to the template using the ngTemplateOutletContext
property. The context object will be available within the template.
Example:
<ng-container *ngTemplateOutlet="template; context: myContext"></ng-container> <ng-template #template let-name let-age="age"> <p>Hello, {{ name }}! You are {{ age }} years old.</p> </ng-template>
Component:
@Component({ selector: 'app-dynamic-template', templateUrl: './dynamic-template.component.html', }) export class DynamicTemplateComponent { myContext = { $implicit: 'John', age: 30 }; }
$implicit
is a default value accessible vialet-variableName
in the template.- Other properties are explicitly passed using
let-variableName="propertyName"
.
4. Reusable Components with Dependencies
To create reusable components that share dependencies, you can:
- Define a
ng-template
for the shared structure. - Use
ngTemplateOutlet
to render the template in different contexts.
Example:
Parent Component HTML:
<ng-container *ngTemplateOutlet="dynamicTemplate; context: context1"></ng-container> <ng-container *ngTemplateOutlet="dynamicTemplate; context: context2"></ng-container> <ng-template #dynamicTemplate let-title let-items="items"> <h2>{{ title }}</h2> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> </ng-template>
Parent Component TS:
@Component({ selector: 'app-parent', templateUrl: './parent.component.html', }) export class ParentComponent { context1 = { title: 'Fruits', items: ['Apple', 'Banana', 'Cherry'] }; context2 = { title: 'Vegetables', items: ['Carrot', 'Broccoli', 'Peas'] }; }
5. Creating Dynamic Components with Shared Services
When using services, you can share dependencies between components dynamically rendered with ngTemplateOutlet
.
Example:
Service:
@Injectable({ providedIn: 'root' }) export class DataService { getData() { return ['Dynamic Item 1', 'Dynamic Item 2']; } }
Component with Shared Template:
<ng-container *ngTemplateOutlet="dynamicTemplate; context: { items: data }"></ng-container> <ng-template #dynamicTemplate let-items="items"> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> </ng-template>
Component TS:
@Component({ selector: 'app-dynamic', templateUrl: './dynamic.component.html', }) export class DynamicComponent { data: string[]; constructor(private dataService: DataService) { this.data = this.dataService.getData(); } }
6. Combining ngTemplateOutlet
with Structural Directives
You can use ngTemplateOutlet
within custom structural directives to create advanced dynamic behaviors.
Example:
Custom Directive:
@Directive({ selector: '[appRepeat]', }) export class RepeatDirective { @Input('appRepeatOf') items: any[] = []; constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<any>) {} ngOnChanges() { this.viewContainer.clear(); this.items.forEach(() => { this.viewContainer.createEmbeddedView(this.templateRef); }); } }
Usage:
<div *appRepeat="let i of [1, 2, 3]"> Item {{ i }} </div>
Best Practices
- Use Templates for Reusability: Define templates in reusable components or directives.
- Keep Context Simple: Pass minimal data to templates to maintain clarity.
- Combine with Services: Share data or dependencies via services to ensure consistency.
- Leverage TemplateRef and ViewContainerRef: For more advanced use cases, you can manually create embedded views.
By combining ngTemplateOutlet
with Angular’s other features, you can build highly flexible and reusable components.
Guys if you will have any kind of query then feel free to comment below.
Ajay
Thanks