Timesaver Authorize directive in Angular

Luka Onikadze
4 min readAug 9, 2020

Authorization is a must thing to do in web applications nowadays. It’s like a morning coffee, you need to drink it to be capable of doing important tasks throughout a day.

There are lots of different use cases and scenarios when it comes to the Authorization, but in my frontend career I’ve seen mostly these two patterns

  • a user can navigate somewhere depending on authorization e.g “User profile page”
  • a user can see some elements depending on authorization e.g “Pay button”, “Sign out”…

In Angular, the first problem is already solved using Route Guards. But in the second one, there are no core concepts on how to do that. The most common solution is to add the *ngIf="isAuthorized" directive on every element, to manage its visibility based on authorization. In order to achieve that, you need to inject some service that stores a user authorization state, assign it to the component variable e.g isAuthorized and then add it to the ngIf directive. By that, you are copy/paste the same code over and over again and it becomes less maintainable, bug-prone, and time-consuming. It would be really nice if we could encapsulate all the logic somewhere, and just use it inside our view. That’s when a structural directive comes into play.

Structural Directive

--

--