It’s trivial in Angular to write small, reusable (and testable!) components to accomplish simple tasks that you might use throughout your application. One such component I had to write the other day was a simple Angular directive to dynamically show or hide (or rather, remove) page elements based on the currently logged in user’s role. The directive itself is crazy simple:
It has a single dependency on a service responsible for reporting the current user’s role, which in my application returns an array along the lines of [100, 101, 999] (Where each number indicates a specific role assigned to that user). The directive also expects a single argument; the permitted roles for the page element that we’ve attached the directive to. Imagine we use the role ID ‘101’ to indicate an admin; the directive usage might look something like this:
Within the link function of the directive, i’m using Lodash to determine the intersection of the roles passed to the directive and the actual roles for the user; the net result being an array of roles for the user that match any roles passed to the directive. If that array is non-zero in length, then at least one of the roles match, and there is nothing for us to do, we’ll let the browser render the element as usual. If there are no matching roles though, we can simply delete the element that the directive is attached to, removing it from the page.
Obviously our role checks are also performed on the backend to ensure no one is accessing something they shouldn’t, but this is a simple way to show/hide elements in your app from users.