So our use case is to create a directive, which shows/hides elements on the page based on our currently authenticated user's permissions. In this article we will go over a very simple use case, but which could easily be extended and used in a real production application. By creating such directive we'll also take a deeper look at the syntax that Angular's ngIf
and ngFor
directives use.
Consider we're having a user object structure that looks like this:
const aUser = {
username: 'juristr',
permissions: [
'permission1',
'permission2',
'permission3'
]
}
This is what we get when the user authenticates. What we want to achieve now is to have a more advanced *ngIf
directive that automatically retrieves information about the authenticated user and hides/shows blocks of our app based on the permissions we define.
For instance, such a custom *hasPermission
directive could work like this:
<div *hasPermission="['can_write', 'can_read']">
Only users with "can_write AND "can_read" permissions can see this.
</div>
By defining such block in our component template, it will automatically be hidden if the user does not have the permissions can_write
and can_read
.
Neat, isn't it 😃. Read the full blog post & how to create such custom directive here »