Angular - Standalone Component
本 Angular 章节将讨论 Standalone component,包括 Angular 团队何时引入它、它的优势、如何创建 standalone components 等内容。
Angular 中的 Standalone Components
在 Angular 中,Standalone components 提供了一种简化的方式来构建 Angular 应用。顾名思义,standalone components 是独立的,不依赖于其他模块或组件。
注意! 是的,standalone components 是独立的;它们不再依赖 @NgModule。如果您尝试将 standalone component 导入到 @NgModule 中,可能会遇到错误。
重要! Standalone components 在 Angular 14 版本中引入。了解更多关于 Angular 各个版本的信息:查看更多
Standalone components 适用于不需要模块依赖的小型应用。然而,在开发大型或复杂应用时,如果组件有强制依赖,这将成为 standalone components 的缺点。
重要! 任何现有的 Angular 应用都可以选择性地逐步采用新的 standalone 风格,而不会产生任何破坏性变更。
Standalone 与 Non-Standalone Components 的对比
下面是区分 standalone 和 non-standalone component 的列表:
| Standalone | Non-Standalone |
|---|---|
| 独立:Standalone components 不依赖 @NgModule。 | 模块依赖:这些组件必须在 @NgModule 中声明才能使用。 |
| 简化结构:适合创建可复用的 components、directives 或 pipes,而无需涉及 Angular modules。 | 复杂结构:适用于更大、更复杂的应用,其中 components 是更大模块结构的一部分。 |
| Standalone @Component 指令包含 standalone: true 和 imports: []。 | Non-standalone component 不包含这些配置。 |
如何创建 Standalone Component?
要在您的 Angular 应用中创建 standalone component,需要运行以下命令:
ng generate component component_name
在 Angular 的最新版本中,此命令会自动创建 standalone component,因为应用默认支持 standalone components。
然而,在 Angular 的旧版本中,运行上述命令可能不会创建 standalone component。在这种情况下,我们需要使用以下命令或手动设置 standalone 属性并指定 imports。
ng generate component component_name --standalone
Standalone component 的初始数据如下所示:
import { Component} from '@angular/core';
@Component({
selector: 'app-root',
imports: [],
templateUrl: './app.html',
styleUrl: './app.css'
})
export class App{
title = 'my-crud-app';
}
其中,
- standalone: true 属性标识此 component 为 standalone component。
- imports 数组是您可以添加此 component 所需的所有依赖的地方。
验证 Standalone Components
您可能想知道如何判断一个 component 是否为 standalone。要在 Angular 中验证 component 是否为 standalone,可以按照以下指南检查:
- Standalone 属性: 检查 component 的 TypeScript 文件(.ts 文件)中的 standalone 属性。如果 standalone 属性设置为 true,则它是 standalone component。
@Component({
selector: 'app-root',
imports: [],
templateUrl: './app.html',
styleUrl: './app.css'
})
Component imports must be standalone component
Standalone Components 的优势
以下是 Standalone components 的一些优势列表:
- 可重用性: 这些组件是自包含的,使它们易于在应用程序的不同部分重用,而无需任何模块依赖。
- 更快的开发: 由于无需在模块中导入,开发者可以快速创建并集成新组件,从而加速开发过程。
- 模块化: Standalone components 实现了模块化方法,有助于更好地组织和维护代码库。