can-it.github.io

@can-it/ngx (NgxCanIt)

An Angular library that provides an easy and efficient way to implement authorization in your application. With NgxCanIt, you can quickly integrate complex authorization scenarios into your app in just a few minutes. npm version

Examples

👉 Source code.

Features

Installation

To install NgxCanIt, you can use npm, yarn, or pnpm. Run one of the following commands in your project directory:

npm install @can-it/ngx
yarn add @can-it/ngx
pnpm add @can-it/ngx

Usage

  1. Import the NgxCanItModule into your Angular application’s module:
import { NgxCanItModule } from '@can-it/ngx';

@NgModule({
  imports: [
    // ...
    NgxCanItModule.forNewScope(),
    // ...
  ],
})
export class AppModule { }

Notice: You can import this NgModule multiple times by using NgxCanItModule.forNewScope() and NgxCanItModule.forChild().

  1. Use the PolicyStore to set the permissions for the current user:
import { Component } from '@angular/core';
import { PolicyStore } from '@can-it/ngx';

@Component({
  selector: 'app-component',
  template: `
    <!-- your component template -->
    <app-products-component></app-products-component>
  `,
})
export class AppComponent implements OnInit {
  constructor(private policyStore: PolicyStore) {}

  ngOnInit(): void {
    this.policyStore.set({
      allow: [
        ['edit', 'products'],
        ['view', 'users'],
      ]
    });
  }
}
  1. Implement authorization logic in your component using the canIt pipe, *canIt directive, or CanItService:
import { Component, OnInit } from '@angular/core';
import { CanItService } from '@can-it/ngx';

@Component({
  selector: 'app-products-component',
  template: `
    <!-- Using *canIt directive -->
    <div *canIt="['edit', 'products'] else notAuthorized">
      <ul>
        <li>product 1</li>
        <li>product 2</li>
        <li>product 3</li>
      </ul>
    </div>
    <ng-template #notAuthorized>
      You cannot access this content.
    </ng-template>


    <!-- Using canIt pipe -->
    <button [class.inactive]="!(['create', 'products'] | canIt | async)">
      New Product
    </button>
  `,
})
export class ProductsComponent implements OnInit {
  constructor(private canItService: CanItService) {}

  ngOnInit() {
    // using CanItService
    const canViewUser = this.canItService.allowTo('view', 'users');
    // ...
  }
}