Search⌘ K

Toggling Templates Dynamically

Explore how to implement dynamic template toggling in Angular applications by creating custom structural directives. Understand how to control DOM elements based on user roles, use Angular services like TemplateRef and ViewContainerRef, and create standalone directives to enhance component flexibility.

We have already seen various use cases for attribute directives. In this lesson, we will learn about structural directives that are not so widely used. A typical scenario in enterprise Angular applications is that users should have access to certain application parts according to their role. We may think that we could use the ngIf built-in directive for this. It would be valid for a simple case, but usually, checking a role involves calling some service to get the current user and extracting their role. We could create a more specific structural directive:

  1. Run the following Angular CLI command to create a permission directive:

Note: The command below is for creating a directive on the local machine using the Angular CLI.

ng generate directive permission
Command to create the directive
  1. Import the Input, TemplateRef, ViewContainerRef, and OnInit artifacts from the @angular/core npm package:

TypeScript 4.9.5
import { Directive, Input, TemplateRef, ViewContainerRef, OnInit } from '@angular/core';
    ...