How to use ngTemplateOutlet in Angular

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 context 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 any case, the ngTemplateOutlet directive will render the template in 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 that you can use to learn.

What is ngTemplateOutlet and how does it work?

In Angular, ngTemplateOutlet is a directive that allows you to insert a template into your view. This directive is used to render the 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 reference object will be used to resolve any variables in the template.

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

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

How to use ngTemplateoutlet in Angular

ngTemplateOutlet is a directive 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 must first 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 use the ngTemplateOutlet directive to insert it into the DOM.

Let’s take a look at the ngTemplateOutlet example:

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

we have another example of many ideas.

Now, in your app.component.ts

Here we have created a dropdown to list the items in the list view’s card; By using *ngTemplateOutlet directive, we can show our content on the page.

import { Component } from '@angular/core';
import { IItem } from './types'; 
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">  
     <li *listItem="let item">
        {{item.header}}: {{item.content}}
  styles: [    `      font-family: Lato;    `  ] 
}) export class AppComponent  { 
 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 command ng gc card-or-list-view To show the data dynamically on the page.

Here we have created methods to show data in list or in card view, and we are using *ngSwitchCase we will show list of user changes on card view and 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';
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 }">  
  <ul *ngSwitchCase="'list'">  
   <h1>List view</h1>    
   <ng-container *ngFor="let item of items">   
     <ng-container *ngTemplateOutlet="listItemTemplate; context: {$implicit: item, other: 2 }">

Pass template to child component

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

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

We can convert the whole template to the child part of the parent template. The method is similar to passing data from parent to child component.

import { Component, TemplateRef, Input } from '@angular/core';
  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>
 <app-child [customTemplate]="parentTemplate"></app-child>`
export class ParentComponent {  }

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

  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 which gives you access to any element or directive in the template. This is useful when you want to manipulate the DOM,

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

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

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

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

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

@ViewChild(‘templateName’) template;

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

now, If you want to show a different template based on a condition, you can use the ngTemplateOutlet directive. This directive lets you specify the template used to display the 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';
 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> 
 <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 display complex data in your Angular applications.

This technology lets you dynamically change the data in your templates based on user input or other factors.

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

Leave a Comment