下面是 Angular 的 NgModule 模式 和 Standalone 模式 的代码对比示例,通过一个简单的 “计数器组件” 展示两种模式的核心区别。
示例:计数器组件 (CounterComponent)
1. 使用 NgModule 模式
项目结构
src/
├── app/
│ ├── app.component.ts
│ ├── app.module.ts
│ ├── counter/
│ │ ├── counter.component.ts
│ │ ├── counter.component.html
│ │ ├── counter.component.css
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CounterComponent } from './counter/counter.component';
@NgModule({
declarations: [ // 声明组件
AppComponent,
CounterComponent
],
imports: [ // 导入依赖模块
BrowserModule
],
providers: [], // 服务注入
bootstrap: [AppComponent] // 指定主组件
})
export class AppModule {}
counter.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css']
})
export class CounterComponent {
count = 0;
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
counter.component.html
<div>
<h1>Counter: {{ count }}</h1>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">Decrement</button>
</div>
运行说明
- 需要在
NgModule中通过declarations声明组件。 - 每次添加新组件时都要手动更新模块文件。
2. 使用 Standalone 模式
项目结构
src/
├── app/
│ ├── app.component.ts
│ ├── counter.component.ts
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
bootstrapApplication(AppComponent)
.catch(err => console.error(err));
app.component.ts
import { Component } from '@angular/core';
import { CounterComponent } from './counter.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [CounterComponent], // 导入 CounterComponent
template: '<app-counter></app-counter>'
})
export class AppComponent {}
counter.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true, // 标记为独立组件
template: `
<div>
<h1>Counter: {{ count }}</h1>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">Decrement</button>
</div>
`,
styles: [`
div { text-align: center; }
button { margin: 0 5px; }
`]
})
export class CounterComponent {
count = 0;
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
关键区别对比
| 特性 | NgModule 模式 | Standalone 模式 |
|---|---|---|
| 组件声明方式 | 必须在模块的 declarations 数组中声明组件 | 每个组件通过 standalone: true 声明,无需模块 |
| 依赖管理 | 通过模块的 imports 管理依赖 | 每个组件的 imports 自己声明依赖 |
| 模块化组织 | 需要维护多个模块文件,管理模块间关系 | 简化为组件即模块,无需显式模块文件 |
| 文件数量 | 大型项目中可能有大量模块文件 | 减少了模块文件数量,更适合小型/中型项目 |
| 适用场景 | 适合复杂的大型应用,有清晰模块化需求 | 适合小型应用、独立组件、快速开发 |
| 迁移难度 | 如果有模块化历史,迁移到 Standalone 会需要较大改动 | 新项目推荐直接使用 Standalone,开发体验更直观 |
选择适合模式
- 如果是 新项目 或者 小型项目,推荐使用 Standalone 模式,开发体验更流畅。
- 如果是 大型项目 或者已有代码使用
NgModule,则可以继续沿用传统的模块化模式,也可以逐步迁移到 Standalone 模式(Angular 兼容两种模式)。
368

被折叠的 条评论
为什么被折叠?



