Reusable Directive For Authorisation in Angular, avoid *ngIf!

User Permissions

First step is to fetch user Permission from a backend API, for now we can declare a static object in our service. Permission is basically an array of strings.

We need *ngIf, right?

We can now create a directive that takes the permissions of the currently authenticated user and shows/hides them appropriately. In practice, a custom *ngIf directive, *ngIf has a * in front, which is a special syntax within Angular, denoting a so-called structural directive.

What is a Directive?

  1. Components — directives with a template.
  2. Structural directives — change the DOM layout by adding and removing DOM elements.
  3. Attribute directives — change the appearance or behavior of an element, component, or another directive.

How custom directive helps?

We can create a custom directive which would basically handle all the conditional and business logic instead of putting logic in *ngIf , it definitely improves the readability and maintainability of the code.

Disable the component in the view

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anjali Verma

Anjali Verma

Web Developer, loves to write about UI technologies