Angular 2 教程

Angular 2 教程

Angular 2+ 是 Google 推出的现代前端框架,采用 TypeScript 开发,以组件化、模块化、依赖注入和响应式编程为核心设计理念。它完全重写了 AngularJS(1.x),成为构建大型企业级单页应用(SPA)的主流框架。

核心特性

  • 组件化架构:一切 UI 都是组件,每个组件由模板、样式和类组成
  • 模块系统:NgModule 组织功能边界,支持懒加载
  • 依赖注入:内置 DI 容器管理服务与对象的创建和生命周期
  • 响应式表单与 RxJS:处理复杂表单和异步数据流

生态工具链

Angular CLI 提供了脚手架、构建、测试、部署的一站式工具链;配合 Angular Material 组件库和官方文档,可以高效开发从简单页面到复杂后台的各类应用。

本教程将带领你从环境搭建开始,逐步掌握 Angular 的完整开发技能。

Angular 2 JavaScript

Angular 2 JavaScript

虽然 Angular 官方推荐使用 TypeScript 开发,但对于熟悉 JavaScript 的开发者,Angular 同样支持用纯 JavaScript(ES6+)编写应用。

基础写法

// app.js - 使用 JS 定义组件
const AppComponent = ng.core.Component({
  selector: 'my-app',
  template: '<h1>Hello {{ name }}!</h1>'
}).Class({
  constructor: function() { this.name = 'Angular'; }
});

// 声明模块并启动
const AppModule = ng.core.NgModule({
  declarations: [AppComponent],
  imports: [ng.platformBrowser.BrowserModule],
  bootstrap: [AppComponent]
}).Class({ constructor: function() {} });

ng.platformBrowserDynamic.platformBrowserDynamic()
  .bootstrapModule(AppModule);

ES6 特性

  • 使用 class 语法替代函数原型
  • 使用 import/export 模块化组织代码
  • 使用箭头函数处理回调与 this 指向

注意事项

纯 JS 开发需要引入 angular2 的 UMD 包,且无法获得类型检查与 IDE 智能提示。建议新项目优先使用 TypeScript,JS 方案仅用于快速原型或学习演示。

Angular 2 TypeScript

Angular 2 TypeScript

TypeScript 是 Angular 2+ 官方推荐的语言,它提供了静态类型、装饰器、接口、泛型等特性,让大型应用更易维护。

环境要求

  • Node.js ≥ 18
  • npm 或 yarn 包管理器
  • @angular/cli 脚手架工具

创建项目

npm install -g @angular/cli
ng new my-app        # 创建项目(自动配置 TypeScript)
cd my-app
ng serve --open      # 启动开发服务器

TypeScript 在 Angular 中的作用

  • 装饰器:@Component、@NgModule、@Injectable 标记元数据
  • 类型标注:定义模型、服务、组件的输入输出类型
  • 访问修饰符:public/private/protected 控制成员可见性

示例组件

@Component({
  selector: 'app-hello',
  template: '<h1>Hello {{ name }}</h1>'
})
export class HelloComponent {
  name: string = 'World';
  constructor() {}
}

通过 tsconfig.json 可以精细控制编译选项,Angular CLI 默认提供了一套最佳实践的配置。

Angular 2 架构

Angular 2 架构

Angular 应用由一系列协同工作的构建块组成,理解整体架构是开发的前提。

核心构建块

  • 模块(NgModule):应用的容器,声明组件、导入依赖、提供服务
  • 组件(Component):带有模板的类,控制屏幕的一部分
  • 模板(Template):HTML 片段,通过数据绑定与组件交互
  • 元数据(Metadata):装饰器提供给框架的配置信息
  • 数据绑定:插值、属性绑定、事件绑定、双向绑定
  • 指令(Directive):操作 DOM 结构的逻辑
  • 服务(Service):封装可复用的业务逻辑,供组件注入
  • 依赖注入(DI):框架自动向组件提供所需服务实例

应用流程

main.ts (平台引导)
  → AppModule (根模块)
    → AppComponent (根组件)
      → 子组件树 (页面视图)

数据流

组件通过输入属性(@Input)接收数据,通过输出事件(@Output)向父组件发送通知;服务层负责数据获取与状态管理,遵循单向数据流原则。

Angular 2 数据显示

Angular 2 数据显示

Angular 通过插值表达式和属性绑定把组件中的数据展示到模板。

插值表达式

<p>当前用户: {{ username }}</p>
<p>年龄: {{ age + 1 }} 岁</p>

属性绑定

<img [src]="user.avatar" alt="头像">
<button [disabled]="isLoading">提交</button>
<div [ngClass]="{'active': isActive}">状态块</div>

内置管道

<p>日期: {{ today | date:'yyyy-MM-dd' }}</p>
<p>金额: {{ price | currency:'CNY' }}</p>
<p>文本: {{ content | uppercase }}</p>

*ngFor 循环

<ul>
  <li *ngFor="let item of items; let i = index">
    {{ i + 1 }}. {{ item.name }}
  </li>
</ul>

*ngIf 条件渲染

<div *ngIf="isLoggedIn; else loginTip">欢迎回来!</div>
<ng-template #loginTip>请先登录</ng-template>

通过 @Input() 属性绑定,父组件可以把数据传给子组件显示,实现组件的复用。

Angular 2 用户输入

Angular 2 用户输入

Angular 通过事件绑定和双向绑定响应用户交互,处理键盘、鼠标、表单等输入。

事件绑定

<button (click)="save()">保存</button>
<input (keyup.enter)="search()" placeholder="回车搜索">
<div (mouseenter)="showTip()" (mouseleave)="hideTip()">悬停我</div>

事件对象

<input (input)="onInput($event)">

onInput(event: any) {
  this.value = event.target.value;
}

双向绑定

<input [(ngModel)]="username" name="username">
<p>你输入的是: {{ username }}</p>

使用 ngModel 需要引入 FormsModule:

import { FormsModule } from '@angular/forms';
@NgModule({ imports: [FormsModule], ... })

模板引用变量

<input #myInput placeholder="示例">
<button (click)="alert(myInput.value)">读取输入</button>

表单提交

<form (ngSubmit)="onSubmit()" #f="ngForm">
  <input name="email" ngModel required>
  <button type="submit" [disabled]="!f.valid">提交</button>
</form>

事件绑定遵循"小写括号 + 事件名"语法,配合模板引用变量可以灵活处理各类用户输入场景。

Angular 2 表单

Angular 2 表单

Angular 提供模板驱动表单和响应式表单两套方案,满足从简单到复杂的表单需求。

模板驱动表单

适合简单表单,通过 ngModel 双向绑定和验证指令:

<form #loginForm="ngForm" (ngSubmit)="login(loginForm.value)">
  <input name="email" ngModel required email placeholder="邮箱">
  <input name="password" ngModel required minlength="6" type="password" placeholder="密码">
  <button type="submit" [disabled]="!loginForm.valid">登录</button>
</form>

响应式表单

适合复杂动态表单,在组件中构建表单模型:

import { FormGroup, FormControl, Validators } from '@angular/forms';

this.profileForm = new FormGroup({
  name: new FormControl('', [Validators.required]),
  email: new FormControl('', [Validators.required, Validators.email]),
  age: new FormControl(18, [Validators.min(1), Validators.max(120)])
});

onSubmit() {
  if (this.profileForm.valid) {
    console.log(this.profileForm.value);
  }
}

模板中绑定响应式表单

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
  <input formControlName="name">
  <input formControlName="email">
  <input formControlName="age" type="number">
  <button type="submit" [disabled]="profileForm.invalid">保存</button>
</form>

内置验证器

required、email、minLength、maxLength、pattern、min、max 等,还可通过自定义验证器函数实现业务规则校验。

Angular 2 模板语法

Angular 2 模板语法

模板是 Angular 应用的视图层,使用 HTML 增强语法描述界面。

插值与绑定总览

{{ title }}                         插值
[property]="value"                   属性绑定
(event)="handler()"                  事件绑定
[(ngModel)]="model"                  双向绑定
#templateVar                       模板引用变量
*ngIf / *ngFor / *ngSwitch         结构指令
[class.active]="cond"               类绑定
[style.color]="colorVar"            样式绑定

模板语句上下文

模板可以访问组件的公有成员、模板引用变量,以及事件中的 $event 对象:

<input (keyup)="logKey($event.key)">

管道链

<p>{{ text | slice:0:20 | uppercase }}...</p>

安全导航符

<p>{{ user?.address?.city }}</p>  <!-- 避免空指针 -->

模板与样式封装

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.css'],
  encapsulation: ViewEncapsulation.Emulated  // 样式隔离
})

Angular 的模板编译器会把模板转换为高效的 JS 指令,在编译期即可捕获大部分绑定错误。

Angular 2 JavaScript 环境配置

Angular 2 JavaScript 环境配置

在使用纯 JavaScript 开发 Angular 时,环境配置与传统 webpack/CLI 项目略有不同。

方式一:CDN 引入

<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/core-js/client/shim.min.js"></script>
  <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
  <script src="https://unpkg.com/reflect-metadata@0.1.8"></script>
  <script src="https://unpkg.com/rxjs@6"></script>
  <script src="https://unpkg.com/@angular/core@latest/bundles/core.umd.js"></script>
  <script src="https://unpkg.com/@angular/common@latest/bundles/common.umd.js"></script>
  <script src="https://unpkg.com/@angular/compiler@latest/bundles/compiler.umd.js"></script>
  <script src="https://unpkg.com/@angular/platform-browser@latest/bundles/platform-browser.umd.js"></script>
  <script src="https://unpkg.com/@angular/platform-browser-dynamic@latest/bundles/platform-browser-dynamic.umd.js"></script>
</head>
<body>
  <my-app>加载中...</my-app>
  <script src="app.js"></script>
</body>
</html>

方式二:CLI 生成后改 .ts 为 .js

Angular CLI 创建的项目默认为 TypeScript,可以在配置中允许 JS 文件,或将业务代码改用 JS 编写并保持 .js 后缀。

常见问题

  • UMD 包顺序必须正确(core → common → compiler → platform)
  • 需要引入 zone.js 才能运行变更检测
  • 模块加载用 SystemJS 或 webpack 配置别名

建议:学习阶段用 CDN 快速验证,正式项目仍推荐 Angular CLI + TypeScript 标准流程。

Angular 教程

Angular 总结与实战

本教程至此覆盖了 Angular 2+ 的核心主题:环境搭建、TypeScript 基础、架构组成、数据展示、用户输入、表单处理和模板语法。

完整示例:一个待办应用

// todo.component.ts
@Component({
  selector: 'app-todo',
  template: `
    <h2>待办事项</h2>
    <input [(ngModel)]="newItem" (keyup.enter)="add()" placeholder="输入事项">
    <ul>
      <li *ngFor="let item of items; let i = index">
        {{ item }} <button (click)="remove(i)">删除</button>
      </li>
    </ul>
  `
})
export class TodoComponent {
  items: string[] = ['学习 Angular'];
  newItem = '';
  add() { if (this.newItem.trim()) { this.items.push(this.newItem.trim()); this.newItem = ''; } }
  remove(i: number) { this.items.splice(i, 1); }
}

下一步学习路线

  1. 服务与依赖注入(数据访问)
  2. 路由(Router)与导航
  3. HttpClient 调用后端 API
  4. Angular 生命周期钩子
  5. 模块懒加载与性能优化
  6. Angular Material 组件库

掌握以上内容后,你就能独立开发完整的 Angular 单页应用。祝学习愉快!

第 1 / 10 节