standalone components 是在 Angular 14 正式引入的(2022 年),可以说是 Angular 框架发展中的一个重大更新!
🌟 什么是 Standalone Component?
传统 Angular 项目中,每个组件都要挂在某个 NgModule 下。但在 Angular 14 起:
✅ 组件可以脱离 NgModule 独立存在!
🚀 从哪个版本开始支持?
| 特性 | 版本 | 状态 |
|---|---|---|
standalone: true | v14 | ✅ 初次引入 |
| 更强大的组合式 API | v15 | ✅ 稳定完善 |
| 默认模板支持 standalone | v17+ | ✅ 默认开启 |
🧱 怎么写一个 Standalone Component?
✅ 以前的写法(v13 及之前):
@NgModule({
declarations: [MyComponent],
imports: [CommonModule]
})
export class MyModule {}
✅ Angular 14+ Standalone 写法:
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-hello',
standalone: true,
imports: [CommonModule],
template: `<p>Hello standalone!</p>`
})
export class HelloComponent {}
🤔 好处有哪些?
✅ 不需要 NgModule
✅ 更容易重用、懒加载
✅ 更贴近现代前端(像 React)
✅ 组合式结构更清晰
✅ 更适合微前端架构
🧪 Angular CLI 创建 standalone 组件:
ng generate component my-component --standalone