If you are in the Angular realm for a good long time, you must be familiar with the concept of directives. Directives are one of the basic building blocks of Angular. It is everywhere. Even components in Angular are in directives with a template.
Directives basically are typescript classes with @Directive
decorators. From the Angular documentation, you can see there are three types of directives
Some common directives that must be familiar to you are: *ngFor(structural)
, *ngIf(structural)
, hidden(attribute)
, NgStyle(attribute)
, etc. The scope of this article will be on the last type: Attribute directives.
Recently on one of my projects, I had a requirement for a simple role-based access system. In one of my modules, the add, edit, delete, or update actions were based on the user role which is determined at the admin level and is configurable. The access information is available on the user login.
How would you implement this?
Initial thoughts were to use *ngIf
or [hidden]
directives in all components with custom logic inside the component’s controller. It looked easy to implement. But how reusable would it be? What if you want to use it in multiple modules, components? Yes, time to introduce a directive!
Like I stated above, directives are typescript classes. You can create a file, conveniently name it access-control.directive.ts
and create your class manually. But I am going to take help from Angular CLI to do this.
ng generate directive access-control
You now have the simplest directive ever, which doesn’t do anything just yet.
import { Directive } from "@angular/core";
@Directive({
selector: "[accessControl]",
})
export class AccessControlDirective {
constructor() {}
}
#typescript #angular #web-development #programming #javascript