Creating Custom Angular Directives: Extending HTML......

Creating Custom Angular Directives: Extending HTML with Ease

Creating Custom Angular Directives: Extending HTML with Ease

What Are Directives in Angular?


Directives are one of the core features of Angular. They allow you to attach behavior to elements in the DOM and modify their appearance or behavior. Angular comes with several built-in directives like ngIf, ngFor, and ngClass, but creating custom directives gives you the power to build functionality tailored to your specific needs.

There are three main types of directives in Angular:


1. Component Directives: These are directives with a template. In fact, every Angular component is technically a directive with a template.


2. Attribute Directives: These directives modify the behavior or appearance of an existing DOM element or component by changing its attributes. Examples include ngClass and ngStyle.


3. Structural Directives: These directives change the DOM layout by adding or removing elements. Examples include ngIf and ngFor.


In this blog, we’ll focus on creating custom structural directives.


Creating a Custom Structural Directive


Step 1: Generate the Directive


ng generate directive RoleBasedDisplay


Step 2: Implement the Directive


import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
 selector: '[appRoleBasedDisplay]'
})
export class RoleBasedDisplayDirective {

 private hasView = false;

 @Input() set appRoleBasedDisplay(role: string) {
  if (role === 'admin') {
   this.showElement();
  } else {
   this.hideElement();
  }
 }

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

 private showElement() {
  if (!this.hasView) {
   this.viewContainer.createEmbeddedView(this.templateRef);
   this.hasView = true;
  }
 }

 private hideElement() {
  if (this.hasView) {
   this.viewContainer.clear();
   this.hasView = false;
  }
 }

}


Explanation:


  • TemplateRef: Represents the embedded template that will be inserted or removed from the DOM.


  • ViewContainerRef: The container where the template will be inserted.


  • @Input(): Allows the directive to accept a role as an input. Based on this role, the directive will decide whether to render the element.


Step 3: Use the Directive


<div *appRoleBasedDisplay="'admin'">
 Only admins can see this content.
</div>




Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts