Unlocking Permissions in Angular 8: A guide to using ngx-permissions for authorization instead of roles

I'm currently utilizing ngx-permissions (https://www.npmjs.com/package/ngx-permissions) within my project to effectively manage user permissions within my application.

While it seems straightforward to authorize roles in the HTML section, permissions seem to be a bit trickier...

Our desired setup is as follows:

HTML:

<div *ngxPermissionsOnly="['voirResources']">1232465</div>

Typescript:

  ngOnInit() {
    const roleMetier: Role = new Role();
    roleMetier.nom = 'ADMIN';
    roleMetier.permissions = ['voirHighlightCard', 'voirResources', 'voirTout', 'voirNextSteps'];
    this.rolesService.addRole(roleMetier.nom, roleMetier.permissions);

    this.permissionsService.loadPermissions(['ADMIN']);
  }

As shown above, I have defined the Admin role along with specific permissions. Subsequently, I load these permissions for current users assigned as admins.

In the HTML code snippet, I include *ngxPermissions="['voirResources']" to restrict the visibility of div content solely to users with the "voirResources" permission.

For a live demo, check out the code on StackBlitz here: https://stackblitz.com/edit/angular-poc-ngx-permissions

I have a couple of inquiries:

  • Is it achievable using ngx-permissions?
  • If not supported by ngx-permissions, do you know of any alternative npm packages that could serve the purpose? I prefer avoiding reinventing the wheel if there's already a reliable solution available ^^

Thank you in advance for your insights!

Answer №1

In order to grant permission, you must utilize

this.permissionsService.addPermission(['seeContent']);
or opt for loadPermission

Here is how you can modify your stackblitz code:

ngOnInit() {
// this.loadUserPermissions();

this.loadUserRole();
console.log(this.rolesService.getRoles());
}

loadUserRole() {
    const userRole: Role = new Role();
    userRole.name = 'ADMIN';
    userRole.permissions = ['seeContent'];

    this.permissionsService.addPermission(['seeContent']);

    this.rolesService.addRole(userRole.name, userRole.permissions);
}

Alternatively, you can update your loadUserPermissions() method as follows:

this.permissionsService.loadPermissions(['seeContent']);

and adjust the sequence of your ngOnInit

this.loadUserPermissions();
this.loadUserRole();

https://stackblitz.com/edit/angular-poc-ngx-permissions-qxi4mz

Answer №2

Using the latest version 8.1.1, accomplishing this task can now be achieved in just a single line of code

this.rolesService.addRoleWithPermissions('ADMIN', ['seeContent']);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Dynamic Updates to a Google Sheets Custom Menu using Typescript

How to Automatically Update a Custom Menu in Google Sheets using Typescript I have successfully set up the following: Dynamically Updating Custom Menu of Google Spreadsheet using Google Apps Script, a demonstration script for dynamically updating the cust ...

linting tool promises there are no missing attributes

When utilizing a component that connects to 'redux' and requires properties to be passed, the linter complains about missing properties. Component1 interface Component1Props { id: number; users: any[]; } const Component1: React.FC<Com ...

Potentially null object in react typescript

In my React application with TypeScript, I have completed the implementation of a chart but encountered an error in the following line: backgroundColor: gradientFill ? gradientFill : chartRef.current.data.datasets[0].backgroundColor, T ...

Limit the number of characters allowed for input in Sweet Alert using Angular

Requirement : The input box must limit the user to a maximum of 20 characters. In my Angular project, I have integrated Sweet Alert for displaying messages. Upon clicking a button, a Sweet Alert with an input type set as password will pop up. I want to ...

Waiting for timeout to pass before proceeding in Angular 2 with Jasmine testing

I have a scenario in my code where a method is returning a part object inside a setTimeout function. The issue arises when testing this method as the test does not wait for the timeout to complete before evaluating the response. How can I ensure that the t ...

Issue with Angular 11: A stream was anticipated but instead an improper object was provided. Acceptable options are Observable, Promise, Array, or Iterable

I'm well aware that there are numerous questions with similar titles and issues. I've dedicated the past day and a half to reading and experimenting with potential solutions, but unfortunately, none have worked for me. My situation varies slightl ...

How can I redirect a page using an axios interceptor in Next.js?

Is there a way to redirect the page in an axios interceptor when dealing with server-side rendering limitations? Unfortunately, I am unable to access the server side context in the axios interceptor. I have tried using next/router but it only works on the ...

How to bind a click event to an anchor tag in Angular 5

Looking to add a click event to an anchor tag in my template: This is how my HTML appears: <a (click)="deleteUser(user)"> <i class="la la-trash"></i> </a> The user variable comes from a previous iteration using *ngFor="let us ...

If the variable state is modified using setInterval, Angular animations will not function as intended

I am attempting to create an animation that changes the opacity of three arrows (intended for user interaction on my website). To achieve this automatically and repeatedly upon loading the webpage, I have implemented a setInterval function within ngOnInit. ...

Mastering the art of utilizing Angular Routing alongside CSS grid for seamless website navigation

My <app-root> layout is pretty straightforward: app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.compone ...

Error: Trying to access the 'checked' property of an undefined variable

Currently, I am working on populating my panel with data from a web API (which is already functioning) while also allowing users to add new points to the list through the panel. This is my checkbox panel: <div class="generalCharacteristicsHover" (mo ...

How to apply animation in Angular 2 to a single element within an *ngFor loop

Is it possible to apply animation to only one element when using *ngFor in Angular? Currently, the animation applies to all elements in the cycle, but I want to target only one element. How can I achieve this? .............................................. ...

Fulfill the promise to retrieve the value contained within

Is there a way to use TypeScript to call the Wikipedia API for retrieving a random page title and save it in a variable for later use? I am struggling with resolving promises as I keep getting ZoneAwarePromise returned. I'm new to both promises and Ty ...

I am interested in preserving a QrCode by converting it into an image

Below is the updated code snippet: [HttpGet("GenerateQrCode")] public ActionResult<string> GenerateQrCode(string sellername, string vatregistration, string timestamp, string invoiceamount, string vatamoun) { string ltr = ((char)0x20 ...

Error message: When attempting to redirect to another route, there is a type error with 'this' as it is implicitly assigned the type 'any'

I'm facing an issue with a component I've built using hooks. I want it to redirect to a different route when a function is called and the server response is received. However, my TypeScript is throwing an error: Type error: 'this' impl ...

How to eliminate or avoid duplicate entries in an array using Angular 2

Within my component, I have set up a subscription to a subject that is returning employee records and storing them in an array. importResults: ImportResults[] = []; constructor( private _massEmpService: MassEmpService ) { } ngOnInit() { // Subsc ...

What is the best way to eliminate unwanted or specific files from a file upload using PrimeNG's p-fileUpload component

I am working on implementing file upload functionality where I need to validate the files upon selection and remove them if they are not valid. .html <p-fileUpload #fileUpload name="datafiles" [accept]=FileExtentionValue [url]=" ...

Tips for accurately defining the return type for querySelector(All) connections

I enjoy doing this particular task, ensuring the types are correct. const qs = document.querySelector.bind(document) as HTMLElementTagNameMap | null; const qsa = document.querySelectorAll.bind(document) as NodeListOf<any>; While hovering over query ...

Ensure that function and class names are retained in the optimized build for Angular 8 to allow for reflection purposes

In an attempt to configure my Angular 8 project build in a way that preserves function and class names (necessary for utilizing reflection and other class name-based features), I have turned to @angular-builders/custom-webpack which allows for overriding w ...

What are the steps for deploying an Angular 2 project to production?

After creating a website using Angular 2 and following the Angular 2 QuickStart Guide, I was able to run it successfully with the command npm start. Now that the site is complete, I need to deploy it for production so that clients can access it. How do I g ...