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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Reproducibility as a Competitive Edge: Why Minimal Config Beats Complex Install Scripts
  • Building a Card Layout Using CSS Subgrid
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder

Trending

  • When a Coding Agent Fixes the Test Instead of the Bug
  • Event Sourcing in Distributed Systems: Architecture, Consistency, and Fault-Tolerant Projections
  • Building IoT Time-Series Applications With Java and Apache IoTDB
  • Decoupling a Data Pipeline From the Tables It Was Never Supposed to Depend On

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

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
·
Oct. 31, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Reproducibility as a Competitive Edge: Why Minimal Config Beats Complex Install Scripts
  • Building a Card Layout Using CSS Subgrid
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook