ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

How to use ng-template & TemplateRef in Angular

In this guide, we will learn what is ng-template and TemplateRef. We also learn how it works and how Angular makes use of them in various directives like ngIf, ngFor & ngSwitch etc. We can use ng-template with ngTemplateOutlet to display the dynamic templates, which is a separate tutorial.

What is ng-Template?

The <ng-template> is an Angular element, which contains the template. A template is an HTML snippet. The template does not render itself on DOM.

To understand let us create a new Angular Application and copy the following code to app.component.html

                              

<h2>Defining a Template using ng-Template</h2>
 
<ng-template>
  <p> Say Hello</p>
</ng-template>
                            
                        

The above code generates the following output. The Angular does not render Say Hello. You won’t even find it as a hidden element in the DOM.

                              
 
//output
 
Defining a Template using ng-Template
 
                            
                        

i.e because ng-template only defines a template. It is our job to tell angular where & when to display it.

There are few ways you can display the template.

  1. Using the ngTemplateOutlet directive.
  2. Using the TemplateRef & ViewContainerRef

Displaying the Template

ngTemplateOutlet

The ngTemplateOutlet, is a structural directive, which renders the template.

To use this directive, first, we need to create the template and assign it to a template reference variable (sayHelloTemplate in the following template).

                              
 
<h1>ng-template & TemplateRef</h1>
 
<h2>Using the ngTemplateOutlet</h2>
 
 
<ng-template #sayHelloTemplate>
  <p> Say Hello</p>
</ng-template>
 

                            
                        

We use the ngTemplateOutlet in the DOM, where we want to render the template.

The following code assigns the Template variable sayHelloTemplate to the ngTemplateOutlet directive using the Property Binding.

                              

<ng-container *ngTemplateOutlet="sayHelloTemplate">
  This text is not displayed
</ng-container> 
 
 
 
//Output
ng-template & TemplateRef
Using the ngTemplateOutlet
Say Hello
 
                            
                        

The content inside the ngTemplateOutlet directive is not displayed. It replaces it with content it gets from the sayHelloTemplate.

TemplateRef & ViewContainerRef

What is TemplateRef?

TemplateRef is a class and the way to reference the ng-template in the component or directive class. Using the TemplateRef we can manipulate the template from component code.

Remember ng-template is a bunch of HTML tags enclosed in a HTML element ng-template

                              

<ng-template>
  <p> Say Hello</p>
</ng-template>
 
                            
                        

To access the above ng-template in the component or directive, first, we need to assign a template reference variable. #sayHelloTemplate is that variable in the code below.

                              

<ng-template #sayHelloTemplate>
  <p> Say Hello</p>
</ng-template>
                            
                        

Now, we can use the ViewChild query to inject the sayHelloTemplate into our component as an instance of the class TemplateRef.

                              

@ViewChild,('sayHelloTemplate', { read: TemplateRef }) sayHelloTemplate:TemplateRef<any>;
 
                            
                        

Now, we need to tell Angular where to render it. The way to do is to use the ViewContainerRef

The ViewContainerRef is also similar to TemplateRef. Both hold the reference to part of the view.

  • The TemplateRef holds the reference template defined by ng-template.
  • ViewContainerRef, when injected to via DI holds the reference to the host element, that hosts the component (or directive).
  • Once, we have ViewContainerRef, we can use the createEmbeddedView method to add the template to the component.

                                  
      constructor(private vref:ViewContainerRef) {
      }
     
      ngAfterViewInit() {
        this.vref.createEmbeddedView(this.sayHelloTemplate);
      }
     
                                
                            

    The template is appended at the bottom.

    Angular makes use of ngTemplate extensively in its structural directives. But it hides its complexities from us.

    ng-template with ngIf

    You might have used ngIf a lot of times. Here is how we use it. We use an * before ngIf

                                  
     
    <label>
      <input [(ngModel)]="selected" type="checkbox">Select Me
    </label>
     
    <div *ngIf="selected">
      <p>You are selected</p>
    </div>
     
                                
                            

    There is another way to write the above code. That is using the ng-template syntax. To do that follow these steps

    1. Create a new element ng-template and bind ngIf to it
    2. Use the property binding syntax [ngIf]="selected" instead of *ngIf="selected"
    3. Move the div element on which ngIf is attached inside the ng-templete
                                  
    
    <label>
      <input [(ngModel)]="selected" type="checkbox">Select Me
    </label>
     
    <ng-template [ngIf]="selected">
      <div>
        <p>You are selected</p>
      </div>
    </ng-template>
     
                                
                            

    The code works just like a normal *ngIf would do.

    Behind the scenes, Angular converts every *ngIf to ng-template Syntax. In fact, it does so every structural directive like ngFor, ngSwitch, ngTemplateOutlet, etc

    How it works

    To understand how structural directives using ng-template works let us look at ttIf directive which we built in the tutorial custom structural directive.The ttIf directive is a simplified clone of *ngIf.

    Create tt-if.directive.ts and add the following code. Also, remember to declare the ttIfDirective in app.module.ts

                                  
    
    import { Directive, ViewContainerRef, TemplateRef, Input } from '@angular/core';
     
    @Directive({ 
      selector: '[ttIf]' 
    })
    export class ttIfDirective  {
     
      _ttif: boolean;
     
      constructor(private _viewContainer: ViewContainerRef,
                  private templateRef: TemplateRef<any>) {
      }
     
     
      @Input()
      set ttIf(condition) {
        this._ttif = condition
        this._updateView();
      }
     
      _updateView() {
        if (this._ttif) {
          this._viewContainer.createEmbeddedView(this.templateRef);
        }
        else {
          this._viewContainer.clear();
        }
      }
     
    }
     
                                
                            

    Open the app.component.html. You can use both <div *ttIf="selected"> and <ng-template [ttIf]="selected"> syntax.

                                  
     
    Show/hide 
    <input type="checkbox" [(ngModel)]="selected">
     
    <div *ttIf="selected">
      Using the ttIf directive via *ttIf
    </div>
     
     
    <ng-template [ttIf]="selected">
      <div>
        <p>Using the ttIf directive via ng-template</p>
      </div>
    </ng-template>
                                
                            
    app.component.ts
                                  
    
    import { Component } from '@angular/core';
     
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      selected=false;
    }
     
     
                                
                            

    Now let us look at the directive code. We are injecting ViewContainerRef and TemplateRef instances in the constructor

                                  
    
     constructor(private _viewContainer: ViewContainerRef,
                 private templateRef: TemplateRef<any>) {
      }
     
                                
                            

    We looked at ViewContainerRef in the previous section. It contains the reference to the host element that hosts our directive.

    In the previous example, we used the ViewChild to get the reference to the template. But it is not possible here. Hence we use the Angular Dependency Injection to inject the template into our directive using the TemplateRef DI token.

    The Template is inserted into the DOM when the condition is true. We do that using the createEmbeddedView method of the ViewContainerRef. The clear removes the template from the DOM

                                  
     this._viewContainer.createEmbeddedView(this.templateRef);
     
                                
                            

    Multiple Structural Directives

    You cannot assign multiple Structural Directives on a single ng-template.

    For Example, the ngIf & ngFor on same div, will result in an an Template parse errors

                                  
     
    <div *ngIf="selected"
         *ngFor="let item of items">
            {{item.name}}
    </div>
     
                                
                            
                                  
    
    Uncaught Error: Template parse errors:
     
    Can't have multiple template bindings on one element. 
    Use only one attribute named 'template' or prefixed with *
                                
                            

    You can use ng-container to move one directive to enclose the other as shown below.

                                  
    
    <ng-container *ngIf="selected">
      <div *ngFor="let item of items">
           {{item.name}}
      </div>
    </ng-container>
     
                                
                            

    ng-template with ngIf, then & else

    The following code shows the ng-template using the ngIf, then & else example.

    Here we use the ng-template specify the template for the then & else clause. We use the template reference variable to get the reference to those blocks.

    In the *ngIf condition we specify the template to render by pointing to the template variable to the then & else condition.

                                  
    
    <h2>Using ngTemplate with ngIf then & else</h2>
     
    <div *ngIf="selected; then thenBlock1 else elseBlock1">
      <p>This content is not shown</p>
    </div>
     
    <ng-template #thenBlock1>
      <p>content to render when the selected is true.</p>
    </ng-template>
     
    <ng-template #elseBlock1>
      <p>content to render when selected is false.</p>
    </ng-template>
     
                                
                            

    The above ngif can be written using the ng-template syntax.

                                  
     
    <ng-template [ngIf]="selected" [ngIfThen]="thenBlock2" [ngIfElse]="elseBlock2">
      <div>
        <p>This content is not shown</p>
      </div>
    </ng-template>
     
    <ng-template #thenBlock2>
      <p>content to render when the selected is true.</p>
    </ng-template>
     
    <ng-template #elseBlock2>
      <p>content to render when selected is false.</p>
    </ng-template>
     
                                
                            

    ng-template with ngFor

    The following ngFor Directive.

                                  
    
    <ul>
       <li *ngFor="let movie of movies; let i=index; let even=even;trackBy: trackById">
         {{ movie.title }} - {{movie.director}}
       </li>
    </ul>
     
                                
                            

    Is written as follows using the ng-template syntax

                                  
    <ul>
    <ng-template 
       ngFor let-movie [ngForOf]="movies" 
       let-i="index" 
       let-even="even"
       [ngForTrackBy]="trackById">
     
       <li>
         {{ movie.title }} - {{movie.director}}
       </li>
     
    </ng-template>
    </ul>
                                
                            

    ng-template with ngSwitch

    The following is the example of ngSwitch.

                                  
     
    <input type="text" [(ngModel)]="num">
     
    <div [ngSwitch]="num">
      <div *ngSwitchCase="'1'">One</div>
      <div *ngSwitchCase="'2'">Two</div>
      <div *ngSwitchCase="'3'">Three</div>
      <div *ngSwitchCase="'4'">Four</div>
      <div *ngSwitchCase="'5'">Five</div>
      <div *ngSwitchDefault>This is Default</div>
    </div>
     
                                
                            

    The above example using the ng-template with ngSwitch. Note that ngSwitch is not a structural directive but ngSwitchCase & ngSwitchDefault are.

                                  
    
    <div [ngSwitch]="num">
      <ng-template [ngSwitchCase]="'1'">
        <div>One</div>
      </ng-template>
      <ng-template [ngSwitchCase]="'2'">
        <div>Two</div>
      </ng-template>
      <ng-template [ngSwitchCase]="'3'">
        <div>Three</div>
      </ng-template>
      <ng-template [ngSwitchCase]="'4'">
        <div>Four</div>
      </ng-template>
      <ng-template [ngSwitchCase]="'5'">
        <div>Five</div>
      </ng-template>
      <ng-template ngSwitchDefault>
        <div>This is default</div>
      </ng-template>
    </div>