用途
本技能用于规范 Angular 项目的架构组织,帮助开发者在构建项目结构或决定组件放置位置时做出一致决策。核心原则是「Scope Rule(作用域规则)」:作用域决定结构,组件放在哪里取决于它的使用范围。
主要能力
Scope Rule(必需)
- 仅被 1 个功能使用的组件:放在 features/[feature]/components/
- 被 2 个及以上功能使用的组件:放在 features/shared/components/
示例结构:
features/
shopping-cart/
shopping-cart.ts # 主组件 = 功能名
components/
cart-item.ts # 仅被 shopping-cart 使用
cart-summary.ts # 仅被 shopping-cart 使用
checkout/
checkout.ts
components/
payment-form.ts # 仅被 checkout 使用
shared/
components/
button.ts # 被 shopping-cart 和 checkout 使用
modal.ts # 被多个功能使用
项目结构
src/app/
features/
[feature-name]/
[feature-name].ts # 主组件(与文件夹同名)
components/ # 功能专属组件
services/ # 功能专属服务
models/ # 功能专属类型
shared/ # 仅用于 2 个及以上功能共用
components/
services/
pipes/
core/ # 应用级单例
services/
interceptors/
guards/
app.ts
app.config.ts
routes.ts
main.ts
文件命名(必需)
不使用 .component、.service、.model 后缀,文件夹本身已表明类型。
- ✅ user-profile.ts ❌ user-profile.component.ts
- ✅ cart.ts ❌ cart.service.ts
- ✅ user.ts ❌ user.model.ts
风格指南
遵循官方文档的部分:
- 使用 inject() 而非构造函数注入
- 使用 class 和 style 绑定而非 ngClass/ngStyle
- 仅模板使用的成员标记为 protected
- inputs、outputs、queries 标记为 readonly
- 处理函数按动作命名(saveUser)而非事件(handleClick)
- 保持生命周期钩子简单,委托给命名良好的方法
- 每个文件一个概念
代码示例:
@Component({...})
export class UserProfileComponent {
// 1. 注入的依赖
private readonly userService = inject(UserService);
// 2. Inputs/Outputs
readonly userId = input.required<string>();
readonly userSaved = output<User>();
// 3. 内部状态
private readonly _loading = signal(false);
readonly loading = this._loading.asReadonly();
// 4. 计算属性
protected readonly displayName = computed(() => ...);
// 5. 方法
save(): void { ... }
}
覆盖官方的部分:
- 官方 user-profile.component.ts → 本技能 user-profile.ts(原因:冗余,文件夹已表明上下文)
- 官方 user.service.ts → 本技能 user.ts(原因同上)
命令
# 新建项目
ng new my-app --style=scss --ssr=false
# 在功能中创建组件
ng g c features/products/components/product-card --flat
# 在功能中创建服务
ng g s features/products/services/product --flat
# 在 core 中创建守卫
ng g g core/guards/auth --functional
使用方式
在构建 Angular 项目结构或决定组件放置位置时触发本技能,按上述 Scope Rule、项目结构、文件命名和风格指南执行。
适用场景
- 新建或重构 Angular 项目结构
- 决定组件应放在功能目录还是共享目录
- 统一文件命名与代码风格
限制
本技能仅提供架构与风格约定,未提供具体版本兼容性、性能或收费相关信息。
资源
https://angular.dev/style-guide