Enhancing Angular Directives: Implementing Permission-Based Conditional Rendering With Else Case
We will walk through the creation of a custom Angular directive that handles permission checks and supports an else case, allowing for cleaner and more maintainable code.
Join the DZone community and get the full member experience.
Join For FreeControlling access to parts of a user interface based on user permissions is essential in modern web applications. Angular provides a robust framework for creating reusable and dynamic components, but it does not offer built-in support for conditional rendering with an else case based on user permissions. In this article, we will walk through the creation of a custom Angular directive that handles permission checks and supports an else case, allowing for cleaner and more maintainable code.
Use Cases
Role-Based Access Control
Many applications have different roles with varying levels of permissions. With our custom directive, you can easily control access to certain features or components based on the user's role.
Feature Toggling
Sometimes, features need to be toggled on or off based on user permissions or feature flags. This directive can conditionally render UI elements based on whether a feature is enabled for the user, simplifying feature management without cluttering the component templates.
Dynamic Content
When content needs to be dynamically rendered based on user permissions or other criteria, this directive provides a clean solution. For example, displaying certain sections of a dashboard based on user permissions enhances the personalized user experience.
Creating the Permission Directive
First, we create a directive that checks for permissions and updates the view accordingly.
Step-By-Step Guide
Setting up the Angular Project
- Ensure you have Angular CLI installed. If not, install it using
npm install -g @angular/cli
. - Create a new Angular project using
ng new permission-directive-demo
. - Navigate to the project directory:
cd permission-directive-demo
.
Creating the Permission Directive
Generate a new directive: ng generate directive hasPermission
.
import { Directive, Input, TemplateRef, ViewContainerRef, ContentChild, AfterContentInit } from '@angular/core';
import { HasPermissionElseDirective } from './has-permission-else.directive';
@Directive({
selector: '[hasPermission]'
})
export class HasPermissionDirective implements AfterContentInit {
private userPermissions: string[] = [];
private requiredPermission: string = '';
@Input()
set hasPermission(val: string) {
this.requiredPermission = val;
this.updateView();
}
@Input()
set userPermissionsInput(val: string[]) {
this.userPermissions = val;
this.updateView();
}
@ContentChild(HasPermissionElseDirective, { static: true })
elseTemplate: HasPermissionElseDirective;
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
ngAfterContentInit() {
this.updateView();
}
private updateView() {
this.viewContainer.clear();
if (this.checkPermission()) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else if (this.elseTemplate) {
this.viewContainer.createEmbeddedView(this.elseTemplate.templateRef);
}
}
private checkPermission(): boolean {
return this.userPermissions.includes(this.requiredPermission);
}
}
Creating the Else Directive
Generate another directive for the else template: ng generate directive hasPermissionElse
.
import { Directive, TemplateRef } from '@angular/core';
@Directive({
selector: '[hasPermissionElse]'
})
export class HasPermissionElseDirective {
constructor(public templateRef: TemplateRef<any>) {}
}
Using the Directives in a Component
Create a component that will use the directives to conditionally render content.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div *hasPermission="'read'" [userPermissionsInput]="userPermissions; else noReadPermission">
This content is only visible to users with the 'read' permission.
</div>
<ng-template #noReadPermission>
<div>
This content is visible when the user does not have the 'read' permission.
</div>
</ng-template>
<div *hasPermission="'write'" [userPermissionsInput]="userPermissions; else noWritePermission">
This content is only visible to users with the 'write' permission.
</div>
<ng-template #noWritePermission>
<div>
This content is visible when the user does not have the 'write' permission.
</div>
</ng-template>
`
})
export class AppComponent {
userPermissions = ['read']; // Fetch user permissions dynamically
}
Running the Application
Serve the application using ng serve
and navigate to http://localhost:4200
to see the directive in action.
Conclusion
By following the steps outlined in this article, you have created a custom Angular directive that supports permission-based conditional rendering with an else case. This approach enhances the flexibility and readability of your Angular templates, allowing you to manage permission-based UI elements more effectively.
Opinions expressed by DZone contributors are their own.
Comments