DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • 50+ Top Angular Interview Questions and Answers
  • Automated Bug Fixing: From Templates to AI Agents
  • Dynamic File Upload Component in Salesforce LWC
  • Enhancing Angular Directives: Implementing Permission-Based Conditional Rendering With Else Case

Trending

  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • AI’s Role in Everyday Development
  • Agentic AI for Automated Application Security and Vulnerability Management

How to Use ngTemplateOutlet in Angular With Example

This powerful feature allows us to reuse templates and keep our code DRY. In Angular, we will show you several ngTemplateOutlet examples you can use to learn.

By 
Akash Chauhan user avatar
Akash Chauhan
·
Oct. 31, 22 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
14.0K Views

Join the DZone community and get the full member experience.

Join For Free

In Angular, we use the ngTemplateOutlet directive to insert an external template into our component's view. This powerful feature allows us to reuse templates and keep our code DRY.

The ngTemplateOutlet directive takes a template reference as its input. This template reference can be a local variable declared in our component's template or a reference to an external template.

In either case, the ngTemplateOutlet directive will render the template into our view.

We can use the ngTemplateOutlet directive to insert a wide variety of content into our view, including other components. 

This makes it an essential tool for building large and complex Angular applications. In Angular, we will show you several ngTemplateOutlet examples you can use to learn.

What Is ngTemplateOutlet and How Does It Work?

In angular, the ngTemplateOutlet is a directive that allows you to insert a template into your view. This directive is used to render a template dynamically.

The ngTemplateOutlet directive takes two input parameters: the first is the name of the template to be rendered, and the second is an optional context object.

The context object will be used to resolve any variables in the template.

The ngTemplateOutlet directive is very powerful and can be used in various ways. One use case for this directive is when you want to render a different template based on some condition.

For example, you could use ngTemplateOutlet to render a different login form for different user types. Another use case for this directive is when you want to reuse a component without having to duplicate code.

How to Use ngTemplateoutlet in Angular

The ngTemplateOutlet is a directive that is used to insert a custom template in place of an existing element in the DOM. This is a powerful feature that can be used to create reusable components.

To use the ngTemplateOutlet directive, you first need to create a custom template. This template can be created using the Angular template syntax or by using an external template file.

Once you have created your custom template, you can then use the ngTemplateOutlet directive to insert it into the DOM.

Let's have a look at the ngTemplateOutlet example:

 
import { Component } from '@angular/core'; 
@Component({  
        selector: 'my-app',
        template: `
<ng-template #estimateTemplate let-lessonsCounter="estimate">
    <div> Approximately {{lessonsCounter}} lessons ...</div>
 </ng-template>
 
<ng-container    *ngTemplateOutlet="estimateTemplate;context:ctx">
 </ng-container>
 `}) 
export class AppComponent {
     totalEstimate = 10;
     ctx = {estimate: this.totalEstimate};
}


Here we have one more example of multiple views.

Now, in your app.component.ts

We have created a dropdown to list the items in the card of list view here; using the *ngTemplateOutlet directive, we can show our content on the page.

 
import { Component } from '@angular/core';
import { IItem } from './types'; 
@Component({  
selector: 'my-app',
template: `
 <label>      Mode:      
 <select [(ngModel)]="mode">        
  <option value="card">card</option>        
  <option value="list">list</option>      
 </select>    </label>   
 <card-or-list-view [mode]="mode" [items]="items"> 
     <div *cardItem="let item" style="border: 1px solid #999999; margin: 10px; padding: 10px">  
      <h1>{{item.header}}</h1> 
      <p>{{item.content}}</p> 
     </div>
     <li *listItem="let item">
        {{item.header}}: {{item.content}}
     </li> 
 </card-or-list-view>
 `,
  styles: [    `      font-family: Lato;    `  ] 
}) export class AppComponent  { 
 mode = 'card';
 items: IItem[] = [
             {    header: 'header 1',    content: 'content 1 modified'  },
             {    header: 'header 2',    content: 'content 2'  },
             {    header: 'header 3',    content: 'content 3'  }, 
             {    header: 'header 4',    content: 'content 4'  }, 
             {    header: 'header 5',    content: 'content 5'  }, 
             {    header: 'Miserable Sunday',    content: 'Sleepy'  }
]; 
}


Now, Create a component card-or-list-view using the command ng g c card-or-list-view to show data dynamically on the page.

Here we have created ways to show the data in the list or in the card view, and we are using *ngSwitchCase we will show the card view and the list of user changes on the dropdown.

 
import { Component, OnInit, ContentChild, TemplateRef, Input } from '@angular/core';
import { CardItemDirective } from '../card-item.directive';
import { ListItemDirective } from '../list-item.directive';
import { IItem } from '../types';
 
@Component({  
selector: 'card-or-list-view',
  templateUrl: './card-or-list-view.component.html'
 }) 
export class CardOrListViewComponent implements OnInit {
   @Input()  items: IItem[] = [];  
   @Input()  mode: 'card' | 'list' = 'card';   // Read in our structural directives as TemplateRefs 
   @ContentChild(CardItemDirective, { read: TemplateRef }) cardItemTemplate; 
   @ContentChild(ListItemDirective, { read: TemplateRef }) listItemTemplate;  
   constructor() { }   
   ngOnInit() {} 
}


In your Html

 
<ng-container [ngSwitch]="mode">  <ng-container *ngSwitchCase="'card'">  
  <h1>Card view</h1>    <ng-container *ngFor="let item of items">  
    <ng-container *ngTemplateOutlet="cardItemTemplate; context: {$implicit: item, other: 1 }">  
    </ng-container>   
 </ng-container> 
 </ng-container>  
  <ul *ngSwitchCase="'list'">  
   <h1>List view</h1>    
   <ng-container *ngFor="let item of items">   
     <ng-container *ngTemplateOutlet="listItemTemplate; context: {$implicit: item, other: 2 }">
     </ng-container>    
   </ng-container> 
 </ul>
</ng-container>


Pass the Template to a Child Component

Angular provides a directive called ngTemplateOutlet that allows you to render a template dynamically. This is particularly useful when you want to reuse a component but with different templates based on the context.

To pass a template to a child component, you first need to create it in the parent component using the Angular template syntax. Then you can reference it by name in the child component using the ngTemplateOutlet directive.

We may transform the entire template into a child portion of the parent template. The method is similar to passing data from parent to child component.

 
import { Component, TemplateRef, Input } from '@angular/core';
 @Component({  
  selector: 'app-parent',
  template: `
  <h1>Parent component</h1>
 <ng-template #parentTemplate> 
   <p>      This Template is defined in Parent.       We will send it to child component    </p>
 </ng-template>
 <app-child [customTemplate]="parentTemplate"></app-child>`
 }) 
export class ParentComponent {  }


And in the child component, we can access this template using the @Input decorator like this.

 
@Component({  
  selector: 'app-child',
  template: `
  <h2>Child component</h2>
   <ng-container *ngTemplateOutlet="customTemplate"> 
   </ng-container>  ` }) 
export class ChildComponent { 
  @Input() customTemplate: TemplateRef; 
}


Use ViewChild to Access the Template

ViewChild is a decorator in Angular that gives you access to an element or directive in the template. This is useful when you want to manipulate the DOM,

For example, to focus on an input or get the position of an element.

ViewChild can be used with any type of element or directive but is most commonly used with components. When using ViewChild with a component, you need to specify the component's name.

ViewChild enables a one-way data binding from the child component to the parent. It is used to access the template of a child component so that it can be modified.

To use ViewChild, you need to first import it into your component.

Once imported, you can then access the template with the following code:

@ViewChild('templateName') template;

This will give you access to the template variable, which you can then use to modify the template as needed.

Now, if you want to show a different template based on some condition, you can use the ngTemplateOutlet directive. This directive lets you specify a template to be used for displaying content.

The ngTemplateOutlet directive will take care of creating and inserting the template into the DOM for you.

 
import { Component, TemplateRef, Input, OnInit, ViewChild, AfterViewInit } from '@angular/core';
 @Component({ 
 selector: 'app-parent',
 template: `
  <h1>Parent component</h1> 
 <ng-template #parentTemplate>  
  <p>      This Template is defined in Parent. We will send it to child component </p> 
 </ng-template> 
 <app-child [customTemplate]="parentTemplate"></app-child>`
 }) 
export class ParentComponent implements OnInit, AfterViewInit {
   @ViewChild('parentTemplate',null) myTemplate:TemplateRef;

   ngAfterViewInit() {    console.log(this.myTemplate)  } 
}


Using the viewChild accessor and the ngTemplateOutlet directive is a great way to show complex data in your Angular applications.

This technique gives you the flexibility to change the data in your templates dynamically based on user input or other factors.

With a little bit of planning, you can use this powerful tool to create sophisticated applications that are responsive and easy to use.

Directive (programming) Template

Published at DZone with permission of Akash Chauhan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • 50+ Top Angular Interview Questions and Answers
  • Automated Bug Fixing: From Templates to AI Agents
  • Dynamic File Upload Component in Salesforce LWC
  • Enhancing Angular Directives: Implementing Permission-Based Conditional Rendering With Else Case

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!