Angular 9 access control using ngx-permission

Angular 6 access control using ngx-permission:

We can’t see any enterprise applications without access control management as this is the most important feature which all the sites must have to avoid security violations and control the views for different user groups.

In angular this can be easily achieved using ngx-permission, I personally used it in my application developments and did not face any issues so far, and even if you face any issues developer is so active to respond as quick as possible.

1. Install ngx-permission

npm install ngx-permissions --save

2. Import into Main Module (app.module)

//Import your library
import { NgxPermissionsModule } from 'ngx-permissions';
import { HttpClientModule } from '@angular/common/http';

And also add the below in your imports array in the same app.module file:

imports: [
NgxPermissionsModule.forRoot(),HttpClientModule
],

3. Import also into Lazy modules

import { NgxPermissionsModule } from "ngx-permissions";

And also import the below in your lazy loaded (.module.ts) file:

imports: [
NgxPermissionsModule.forChild()
],

4. Import & configuration in your components (Main or sub components)

import { NgxPermissionsService } from "ngx-permissions";
import { HttpClient } from "@angular/common/http";

Constructor:

constructor(private permissionsService: NgxPermissionsService,
private http: HttpClient){

}

NgOnInit:

ngOnInit(): void {
const perm = ["EDITOR"];
this.permissionsService.loadPermissions(perm);
this.http.get('url').subscribe((permissions) => {
this.permissionsService.loadPermissions(perm);
})
}

url is the one which gets the roles from your backend application.

5. Control the access in your view:

<div class="nested-menu" *ngxPermissionsOnly="['ADMIN']">
<a class="list-group-item" (click)="addExpandClass('banner')"> <span><i
class="fa fa-image"></i>&nbsp;{{ 'Banner' | translate }}</span>
</a>
</div>

If your getting any other issues, have a look at this link.

Thanks for reading this article.

Leave a Reply