Dynamically switching between templates in angular

In this tutorial, lets see how to dynamically switch between different templates in angular.

There may be some situations, where you have to switch between different templates based on certain conditions in your angular component. In this article, we shall see how to switch between templates based on button click event.

Create a new angular project

Create a new angular application using

ng new template-tutorial

Once the application has been created by angular cli to check the initial result of the application enter.

ng serve --o

Create a component

Let's create a component named DynamicTemplate using the below command.

ng g c dynamic-template

Modify the component's code

In dynamic-template.component.ts file modify the code as below.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dynamic-template',
  templateUrl: './dynamic-template.component.html',
  styleUrls: ['./dynamic-template.component.css']
})
export class DynamicTemplateComponent implements OnInit {

  private role = 'user';
  constructor() { }

  ngOnInit() {
  }

  toggleRole() {
    this.role = this.role === 'admin' ? 'user' : 'admin';
  }
}

Here, we create a variable named role, which can have either user or admin as value.

When calling toggleRole() function, the values of the role variable will be toggled between admin and user.

Modify the component's html

In the dynamic-template.component.html, we shall modify the code as below.

<button (click)='toggleRole()'>
    {{ role === 'admin' ? 'Admin':'User'}}
</button>

<ng-container *ngIf='role === "admin" then adminTemplate else userTemplate'>
</ng-container>

<ng-template #adminTemplate>
    <p>Welcome Admin</p>
</ng-template>

<ng-template #userTemplate>
    <p>Welcom User</p>
</ng-template>

Whenever the role is admin then, adminTemplate will be loaded and whenever the role is user then, userTemplate will be loaded.

We have created a button whose label changes to Admin when the value of role is admin and its label changes to User when the value of the role is user.

When the button is clicked we call the toggleRole() function.

<ng-container *ngIf='role === "admin" then adminTemplate else userTemplate'>
</ng-container>

The ng-container element will check the value of role variable. If the value is admin it would select the adminTemplate and host it inside it. If the value is user the userTemplate will be loaded in the ng-container.

Note

The ng-container element will not be added to the DOM like other elements. Instead of using ng-container if we use div then it would add div element to the DOM, which is not needed. So its better to use ng-container.

Now add the selector string of the DynamicTemplateComponent to app.component.html or any other component.

Run the app using

ng serve --o

Now, whenever we click the button it would toggle between different templates.


Most Read