@casl/angular

中文文档
10.2.0发布于 2026/10/30MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 6.7万

Angular module for CASL which makes it easy to add permissions in any Angular app

原始使用文档
文档目录11 节
  1. Installation
  2. Configure AppModule
  3. Update Ability instance
  4. Check permissions in templates using AbilityService
  5. Signals support
  6. Explain permission checks with whyCan and whyCannot
  7. Create permission signals with defer* methods
  8. Check permissions in templates using pipe (deprecated)
  9. TypeScript support
  10. Want to help?
  11. License

CASL Angular

@casl/angular NPM version Support

This package allows to integrate @casl/ability with Angular application. It provides deprecated AblePipe, AblePurePipe and new AbilityService and AbilityServiceSignal to Angular templates, so you can show or hide components, buttons, etc based on user ability to see them.

Installation

npm install @casl/angular @casl/ability
# or
yarn add @casl/angular @casl/ability
# or
pnpm add @casl/angular @casl/ability

Configure AppModule

To add pipes into your application's templates, you need to import the one you need

import { NgModule } from '@angular/core';
import { AblePipe } from '@casl/angular';
import { createMongoAbility, Ability } from '@casl/ability';

@NgModule({
  imports: [
    // other modules
    AblePipe
  ],
  providers: [
    { provide: Ability, useValue: createMongoAbility() }
  ]
  // other properties
})
export class AppModule {}

Read CASL and TypeScript to get more details about MongoAbility type configuration.

Update Ability instance

Majority of applications that need permission checking support have something like AuthService or LoginService or Session service (name it as you wish) which is responsible for user login/logout functionality. Whenever user login (and logout), we need to update Ability instance with new rules.

Let's imagine that server returns user with a role on login:

import { Ability, AbilityBuilder } from '@casl/ability';
import { Injectable } from '@angular/core';

@Injectable({ provideIn: 'root' })
export class Session {
  #token: string

  constructor(@Inject(Ability) private ability: MongoAbility) {}

  login(details) {
    const params = { method: 'POST', body: JSON.stringify(details) };
    return fetch('path/to/api/login', params)
      .then(response => response.json())
      .then((session) => {
        this.updateAbility(session.user);
        this.#token = session.token;
      });
  }

  private updateAbility(user) {
    const { can, rules } = new AbilityBuilder(createMongoAbility);

    if (user.role === 'admin') {
      can('manage', 'all');
    } else {
      can('read', 'all');
    }

    this.ability.update(rules);
  }

  logout() {
    this.#token = null;
    this.ability.update([]);
  }
}

See Define rules to get more information of how to define Ability.

Then use this Session service in LoginComponent:

import { Component } from '@angular/core';
import { Session } from '../services/Session';

@Component({
  selector: 'login-form',
  template: `
    <form (ngSubmit)="login()">
      <input type="email" [(ngModel)]="email" />
      <input type="password" [(ngModel)]="password" />
      <button type="submit">Login</button>
    </form>
  `
})
export class LoginForm {
  email: string;
  password: string;

  constructor(private session: Session) {}

  login() {
    const { email, password } = this;
    return this.session.login({ email, password });
  }
}

Check permissions in templates using AbilityService

AbilityService is a service that provides ability$ observable. This observable injects provided in DI Ability instance and emits it each time its rules are changed. This allows efficiently use permissions checks, especially in case we use ChangeDetectionStrategy.OnPush.

Let's first see how it can be used in any component:

@Component({
  selector: 'my-home',
  template: `
    @if (ability$ | async as ability) {
      <h1>Home Page</h1>
      @if (ability.can('create', 'Post')) {
        <button>Create Post</button>
      }
    }
  `
})
export class HomeComponent {
  readonly ability$: Observable<AppAbility>;

  constructor(abilityService: AbilityService<AppAbility>) {
    this.ability$ = abilityService.ability$;
  }
}

It also can be safely used inside *ngFor and other directives. If we use ChangeDetectionStrategy.OnPush, it will give us additional performance improvements because ability.can(...) won't be called without a need.

This approach works good from performance point of view because it creates only single subscription per component (not per check as in case of ablePure pipe) and doesn't require our component to use Default or OnPush strategy.

But let's also see how we can do permission checks using pipes and what are performance implications of that:

Signals support

The latest version of @casl/angular also supports new signal. To utilize it in your app, instead of AbilityService use AbilityServiceSignal:

import { AbilityServiceSignal } from '@casl/angular';
import { AppAbility } from './AppAbility';

@Component({
  selector: 'my-home',
  template: `
      <h1>Home Page</h1>
      @if (can('create', 'Post')) {
        <button>Create Post</button>
      }
  `
})
export class HomeComponent {
  private readonly abilityService = inject<AbilityServiceSignal<AppAbility>>(AbilityServiceSignal);
  protected readonly can = this.abilityService.can;
}

Explain permission checks with whyCan and whyCannot

AbilityServiceSignal whyCan and whyCannot methods help to answer the question of why action is allowed or defined:

const abilityService = inject<AbilityServiceSignal<AppAbility>>(AbilityServiceSignal);

abilityService.update([
  { action: 'create', subject: 'Post', reason: 'You can create posts' },
  {
    inverted: true,
    action: 'delete',
    subject: 'Post',
    reason: 'Only administrators can delete posts'
  }
]);

abilityService.whyCan('create', 'Post'); // { reason: 'You can create posts' }
abilityService.whyCan('delete', 'Post'); // null
abilityService.whyCannot('delete', 'Post'); // { reason: 'Only administrators can delete posts' }
abilityService.whyCan('update', 'Post'); // null
abilityService.whyCannot('update', 'Post'); // { reason: undefined }
abilityService.whyCannot('create', 'Post'); // null

Expose these methods to templates the same way as can and use them like this:

@if (whyCannot('delete', 'Post'); as forbidden) {
  <span>{{ forbidden.reason || 'You cannot delete posts' }}</span>
} @else {
  <button (click)="deletePost()">Delete Post</button>
}

A matching inverted rule without a reason returns an object with reason: undefined when the method's condition is met. This keeps a denial truthy even when no explanation is available.

Create permission signals with defer* methods

The defer* methods return computed signals. Each argument (action, subject, or optional field) can be a plain value or a signal. The returned signal recalculates when the ability's rules or any signal argument changes.

Create these signals once, for example in component field initializers, and read them in the template:

import { Component, inject, input } from '@angular/core';
import { AbilityServiceSignal } from '@casl/angular';
import type { AppAbility } from './AppAbility';

@Component({
  selector: 'post-action',
  template: `
    @if (whyCannotPerformAction(); as forbidden) {
      <p>{{ forbidden.reason || 'This action is forbidden' }}</p>
    } @else {
      <button>Perform action</button>
    }
  `
})
export class PostActionComponent {
  private readonly abilityService = inject<AbilityServiceSignal<AppAbility>>(AbilityServiceSignal);
  readonly action = input.required<'create' | 'delete'>();

  protected readonly whyCannotPerformAction = this.abilityService.deferWhyCannot(this.action, 'Post');
}

The parent supplies the action, for example <post-action [action]="'delete'" />. The permission signal updates whenever that input changes.

Pass the signal itself (this.action) to track its changes. Passing its current value (this.action()) fixes that argument to the value it had when the deferred check was created. The deferWhy* methods preserve the null and missing-reason behavior of why* methods; use deferCan or deferCannot when you only need a boolean permission check.

Check permissions in templates using pipe (deprecated)

To check permissions in any template you can use AblePipe:

@if ('create' | able: 'Post') {
  <a (click)="createPost()">Add Post</a>
}

TypeScript support

This package is written in TypeScript, so it will warn you about wrong usage.

It may be a bit tedious to use application specific abilities in Angular app because everywhere you inject Ability instance you will need to import its generic parameters:

import { Ability } from '@casl/ability';
import { Component } from '@angular/core';
import { AppAbilities } from '../services/AppAbility';

@Component({
  selector: 'todo-item'
})
export class TodoItem {
  constructor(
    private ability: Ability<AppAbilities>
  ) {}
}

To make the life easier, you can use AbilityClass<TAbility> class to utilize Companion object pattern:

import { Ability, AbilityClass } from '@casl/ability';

type Actions = 'create' | 'read' | 'update' | 'delete';
type Subjects = 'Article' | 'User';

export type AppAbility = MongoAbility<[Actions, Subjects]>;
export const AppAbility = Ability as AbilityClass<AppAbility>;

And use AppAbility everywhere in your app:

import { NgModule } from '@angular/core';
import { AppAbility } from './services/AppAbility';

@NgModule({
  // other configuration
  providers: [
    { provide: AppAbility, useValue: createMongoAbility() },
  ]
})
export class AppModule {}

Want to help?

Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for contributing.

If you'd like to help us sustain our community and project, consider to become a financial contributor on Open Collective

See Support CASL for details

License

MIT License

版本与发布记录

@casl/angular 共发布 68 个版本,首次发布于 2018/03/18;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
10.2.0latest2026/10/3010 天前
10.1.02026/10/2811 天前
10.0.32026/08/093 个月前
10.0.12026/07/074 个月前
10.0.02026/05/215 个月前
10.0.0-rcnext2026/05/086 个月前

其他发布通道:canary → 0.1.0-alpha.ade5be4a,next → 10.0.0-rc。

关于 @casl/angular 的常见问题

@casl/angular 是什么?

Angular module for CASL which makes it easy to add permissions in any Angular app

如何安装 @casl/angular?

在项目目录运行 npm install @casl/angular,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:rxjs(^7.5.5)、tslib(^2.0.0)、@angular/core(^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0 || ^22.0.0)、@casl/ability(^7.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@casl/angular 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@casl/angular 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@casl/angular 可以商用吗?

@casl/angular 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@casl/angular 的下载量有多少?

根据 npm 官方下载统计,@casl/angular 在 2026/10/09 – 2026/11/07 这 30 天内被下载 66,803 次,日均约 2,227 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@casl/angular 还在维护吗?

最新版本 10.2.0 发布于 2026/10/30(10 天前);至今共发布 68 个版本,其中过去 12 个月发布了 8 个;首次发布于 2018/03/18。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。