How to use ngTemplateOutlet in angular with example - Akashminds

 

ngTemplateOutlet-Angular

In Angular, we use the ngTemplateOutlet directive to insert an external template into our component's view. This is a powerful feature that 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 it can be 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 that you can use to learn.

Learning objectives

  • What is ngTemplateOutlet.
  • How to use ngTemplateoutlet in angular.
  • ngTemplateOutlet exmaple 
  • Pass template to a Child Component
  • Use ViewChild to Access the template
  • Summary

What is ngTemplateOutlet and how it works

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 a variety of 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 the 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 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};
  
}

Check this example on starblitz

Here we have one more example multiple views .

Now, in your app.component.ts


We have created a dropdown to list the items in card of list view here , using *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 command ng g c card-or-list-view to show data dynamically on the page.

Here we have created  we 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 on user change on 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>

Check this example on starblitz


Pass 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 @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)
  }
 
}


Summary


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.

Post a Comment

0 Comments