Chapter 01

Angular 简介与环境搭建

了解 Angular 的设计哲学、版本演进与新特性,搭建开发环境,运行你的第一个 Angular 应用

1. Angular 是什么

Angular 是由 Google 开发并维护的企业级前端框架,于 2016 年发布 Angular 2(对原 AngularJS 1.x 的完全重写)。它不是一个"库",而是一个完整的解决方案:内置路由、HTTP 客户端、表单验证、依赖注入、国际化、动画等模块,开箱即用。

Angular 的核心设计理念是约定优于配置——框架为大型团队提供强约束的项目结构和最佳实践,使不同开发者编写的代码风格高度一致,大幅降低维护成本。

ℹ️

命名说明:AngularJS 指 1.x 版本(已停止维护);Angular 指 2+ 版本(现代 Angular)。本教程讲述 Angular 18,所有示例基于 Angular 17/18 特性。

2. Angular vs React vs Vue 定位对比

三大框架各有侧重,选型前理解它们的定位差异非常重要。

维度AngularReactVue
类型完整框架UI 库渐进式框架
语言TypeScript(强制)JS/TS(可选)JS/TS(可选)
路由内置需第三方内置
HTTP内置 HttpClient需第三方需第三方
表单内置双模式需第三方内置(v-model)
学习曲线陡峭中等平缓
适用场景大型企业应用中大型、灵活中小型、快速

何时选 Angular:团队规模大(10人以上)、需要强约束防止代码风格分散、项目生命周期长、企业内部应用、金融/政务/医疗系统——Angular 的严格结构在这些场景下优势明显。

3. 版本演进:Angular 17 / 18 重要新特性

Angular 17(2023年11月)

Angular 18(2024年5月)

⚠️

Signals 是趋势:Angular 正在逐步将响应式基础从 Zone.js + RxJS 迁移到 Signals。新项目建议优先学习 Signals,但 RxJS 在复杂异步场景仍不可替代。

4. 安装 Angular CLI

Angular CLI(Command Line Interface)是开发 Angular 应用的官方工具,用于创建项目、生成代码、运行服务器、构建生产包等。

环境准备

# 检查 Node.js 版本(需要 18.x 或 20.x)
node --version
npm --version

# 全局安装 Angular CLI
npm install -g @angular/cli

# 验证安装
ng version

运行 ng version 后,你会看到类似如下输出,确认版本正确:

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 18.x.x
Node: 20.x.x
Package Manager: npm 10.x.x

5. ng new:创建 Angular 项目

# 创建新项目(交互式)
ng new my-angular-app

# 创建时回答以下问题:
# ? Which stylesheet format would you like to use? CSS / SCSS / SASS / LESS
# ? Do you want to enable Server-Side Rendering (SSR)? Yes / No

# 指定参数(跳过交互)
ng new my-app --style=scss --ssr=false --routing=true

# 进入项目目录
cd my-angular-app

# 启动开发服务器
ng serve

# 或者指定端口
ng serve --port 4200 --open
ℹ️

--open 标志ng serve --open 会在启动后自动打开浏览器,访问 http://localhost:4200。开发服务器支持热模块替换(HMR),修改代码后页面自动刷新。

6. 项目结构解析

一个刚创建的 Angular 18 项目(Standalone 模式)结构如下:

my-angular-app/
├── src/
│   ├── app/
│   │   ├── app.component.ts       # 根组件
│   │   ├── app.component.html     # 根组件模板
│   │   ├── app.component.scss     # 根组件样式
│   │   ├── app.component.spec.ts  # 根组件测试
│   │   └── app.config.ts          # 应用配置(替代 AppModule)
│   ├── assets/                    # 静态资源
│   ├── environments/              # 环境变量
│   │   ├── environment.ts         # 开发环境
│   │   └── environment.prod.ts    # 生产环境
│   ├── index.html                 # HTML 入口
│   ├── main.ts                    # 应用引导
│   └── styles.scss                # 全局样式
├── angular.json                   # Angular 工作区配置
├── tsconfig.json                  # TypeScript 配置
├── tsconfig.app.json              # 应用 TS 配置
└── package.json

main.ts — 应用引导

// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console.error(err));

app.config.ts — 应用配置

// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(),
  ]
};

7. 常用 CLI 命令

命令说明
ng serve启动开发服务器(默认 4200 端口)
ng build构建应用(开发模式)
ng build --configuration production生产构建(压缩、AOT、Tree Shaking)
ng generate component foo生成组件(缩写 ng g c foo
ng generate service bar生成服务(缩写 ng g s bar
ng test运行单元测试(Karma + Jasmine)
ng lint代码质量检查(ESLint)
ng update升级 Angular 版本

8. 核心名词解释

9. 生成第一个组件

# 生成 HelloWorld 组件
ng generate component hello-world
# 生成的文件:
# src/app/hello-world/hello-world.component.ts
# src/app/hello-world/hello-world.component.html
# src/app/hello-world/hello-world.component.scss
# src/app/hello-world/hello-world.component.spec.ts
// hello-world.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-hello-world',
  standalone: true,
  imports: [],
  template: `
    <div class="hello">
      <h1>Hello, Angular 18!</h1>
      <p>当前时间:{{ currentTime }}</p>
    </div>
  `,
  styles: [`
    .hello { padding: 20px; text-align: center; }
  `]
})
export class HelloWorldComponent {
  currentTime = new Date().toLocaleTimeString();
}

本章小结:Angular 是 Google 出品的完整企业级框架,内置了前端开发所需的全套工具。Angular 18 带来了 Signals 稳定化、Zoneless 实验性支持等重要特性。下一章我们深入组件与模板语法。