Banner

Angular v22

2026-11-06

截至 2026 年 11 月,Angular 最新稳定版本是 v22。上手路线可以按“环境 → 项目 → 组件 → 模板 → 路由 → 表单 → 信号 → 资源请求”来走。下面是一份精简版教程。

1. 准备环境

先确认 Node.js 和 npm:

node -v
npm -v

Angular v22 要求 TypeScript 6,并且已不再支持 Node 20。如果你的 Node 版本较旧,建议先用 nvm 升级到较新的 LTS 版本。

安装 Angular CLI:

npm install -g @angular/cli

验证:

ng version

2. 创建第一个项目

ng new my-app
cd my-app
ng serve --open

浏览器打开 http://localhost:4200,就能看到初始页面。

3. 修改根组件

打开 src/app/app.component.ts,修改标题:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = '我的第一个 Angular 应用';
}

再打开 src/app/app.component.html:

<h1>{{ title }}</h1>

保存后浏览器会自动刷新。

4. 生成一个子组件

ng generate component components/hero-list

这会生成组件的 TS、HTML、CSS 和测试文件。然后在模板里使用新组件:

<app-hero-list></app-hero-list>

5. 使用新控制流语法

Angular 现在推荐使用 @if、@for、@switch,而不是旧的 *ngIf、*ngFor。

@if (heroes.length > 0) {
  <ul>
    @for (hero of heroes; track hero.id) {
      <li>{{ hero.name }}</li>
    } @empty {
      <li>暂无英雄</li>
    }
  </ul>
}

6. 理解 Signals

Signals 是 Angular 新的响应式核心,适合管理状态和派生数据。

import { Component, signal, computed } from '@angular/core';

@Component({
  selector: 'app-hero-list',
  templateUrl: './hero-list.component.html'
})
export class HeroListComponent {
  heroes = signal([
    { id: 1, name: 'Magneta' },
    { id: 2, name: 'Narco' }
  ]);

  count = computed(() => this.heroes().length);
}

模板中读取信号需要加括号:

<p>英雄数量:{{ count() }}</p>

7. 添加路由

ng generate component pages/dashboard
ng generate component pages/heroes

然后在路由配置里添加路径:

import { Routes } from '@angular/router';

export const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: 'dashboard', loadComponent: () => import('./pages/dashboard/dashboard.component').then(m => m.DashboardComponent) },
  { path: 'heroes', loadComponent: () => import('./pages/heroes/heroes.component').then(m => m.HeroesComponent) }
];

模板里使用:

<nav>
  <a routerLink="/dashboard">Dashboard</a>
  <a routerLink="/heroes">Heroes</a>
</nav>

<router-outlet></router-outlet>

8. 发起 HTTP 请求

Angular v22 中,resource、rxResource、httpResource 已稳定,可以用信号方式处理异步数据。

import { Component, inject } from '@angular/core';
import { httpResource } from '@angular/common/http';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html'
})
export class HeroesComponent {
  heroes = httpResource(() => '/api/heroes');
}

模板中读取:

@if (heroes.value(); as list) {
  <ul>
    @for (hero of list; track hero.id) {
      <li>{{ hero.name }}</li>
    }
  </ul>
}

9. 推荐学习顺序

阶段重点目标
入门CLI、组件、模板能跑通 Hello World
基础@if、@for、路由能做多页面导航
状态Signals、computed、effect理解响应式数据流
表单Reactive Forms、Signal Forms能处理复杂表单
进阶httpResource、懒加载、性能优化能搭建企业级应用

10. 值得重点看的新变化

  • OnPush 成为默认变更检测策略:组件默认更偏向精细更新。
  • Signal Forms 稳定:表单和验证可以更自然地与 Signals 结合。
  • 独立组件成为标配:新项目不再必须写 NgModule。
  • Webpack 支持被弃用:工程化方向更偏向现代构建工具链。
17