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
ng generate directive RoleBasedDisplay
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; } } }
Step 3: Use the Directive
<div *appRoleBasedDisplay="'admin'"> Only admins can see this content. </div>