DEV Community

Cover image for Extend the *ngIf Syntax to Create a Custom Permission Directive
Juri Strumpflohner for Angular

Posted on • Updated on • Originally published at

Extend the *ngIf Syntax to Create a Custom Permission Directive

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: [
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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 ยป

Top comments (1)

mfaghfoory profile image
Meysam Faghfouri

Thanks for this useful article