前言
Angular 是由 Google 维护的企业级前端框架 ,基于 TypeScript 开发,内置路由、表单、HTTP、依赖注入等全套解决方案,适合中大型后台管理系统、企业级应用开发。本文整理了 Angular 从入门到实战的全套基础知识点 ,每个知识点搭配可直接运行的代码示例,新手也能快速上手!
适用版本:Angular 14+ / 18+(长期支持版)阅读对象:前端新手、Vue/React 转 Angular 开发者
1. Angular 核心概述
核心特点
- 完整的企业级框架(全家桶,无需额外集成第三方库)
- 强类型:基于 TypeScript 开发
- 内置依赖注入 (DI)、路由、表单、HTTP 客户端
- 单向数据流 + 可选双向绑定
- 适合大型团队、长期维护的项目
核心组成
- 模块 (Module) :组织应用的最小单元
- 组件 (Component) :页面的最小单元
- 服务 (Service) :公共逻辑封装
- 指令 / 管道 / 路由:扩展功能
2. 环境搭建与项目创建
2.1 安装 Angular CLI
bash 运行
bash
# 全局安装 Angular 脚手架
npm install -g @angular/cli
# 验证安装
ng version
2.2 创建新项目
bash 运行
ini
# 创建项目(支持路由、SCSS、严格模式)
ng new angular-demo --routing --style=scss --strict
# 进入项目
cd angular-demo
# 启动项目(默认端口4200)
ng serve --open
2.3 常用 CLI 命令
bash 运行
bash
# 创建组件
ng generate component components/home
# 简写
ng g c components/home
# 创建服务
ng g s services/http
# 创建路由模块
ng g m app-routing --module=app --flat
3. 核心概念:模块 (Module)
定义
模块是 Angular 应用的组织结构 ,一个应用至少有一个根模块 AppModule。
核心作用
- 声明组件、指令、管道
- 导入依赖模块
- 提供服务
- 启动应用
示例:根模块 app.module.ts
typescript 运行
typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
// 路由模块
import { AppRoutingModule } from './app-routing.module';
// 根组件
import { AppComponent } from './app.component';
// 自定义组件
import { HomeComponent } from './components/home/home.component';
@NgModule({
// 声明:当前模块的组件/指令/管道
declarations: [
AppComponent,
HomeComponent
],
// 导入:依赖的其他模块
imports: [
BrowserModule,
AppRoutingModule
],
// 提供:全局服务
providers: [],
// 启动:根组件
bootstrap: [AppComponent]
})
export class AppModule { }
4. 组件 (Component) 基础
定义
组件是 Angular 应用的页面最小单元 ,由 HTML 模板 + TS 逻辑 + CSS 样式 组成。
组件结构
xxx.component.ts:逻辑 / 数据xxx.component.html:模板xxx.component.scss:样式xxx.component.spec.ts:测试文件
示例:自定义组件
typescript 运行
typescript
// home.component.ts
import { Component } from '@angular/core';
@Component({
// 组件选择器(HTML标签)
selector: 'app-home',
// 模板路径
templateUrl: './home.component.html',
// 样式路径
styleUrls: ['./home.component.scss']
})
export class HomeComponent {
// 组件数据
title = 'Angular 入门组件';
// 方法
sayHello() {
alert('Hello Angular!');
}
}
html 预览
xml
<!-- home.component.html -->
<div class="home">
<h2>{{ title }}</h2>
<button (click)="sayHello()">点击我</button>
</div>
5. 模板基础语法
5.1 插值表达式
作用:渲染组件中的变量
html 预览
css
<h1>{{ 变量名 }}</h1>
<p>{{ 1 + 1 }}</p>
<p>{{ name.toUpperCase() }}</p>
5.2 属性绑定
作用:给 HTML 标签动态绑定属性
html 预览
xml
<!-- 原生属性 -->
<img [src]="imgUrl" alt="图片">
<!-- 类名绑定 -->
<div [class.active]="isActive">激活状态</div>
<!-- 样式绑定 -->
<div [style.color]="textColor">文字颜色</div>
6. 数据绑定(单向 / 双向)
6.1 单向绑定
- 组件 → 模板 :
[] - 模板 → 组件 :
()
6.2 双向绑定(核心)
依赖 FormsModule,用于表单数据同步
html 预览
xml
<input [(ngModel)]="username" placeholder="请输入用户名">
<p>你输入的用户名:{{ username }}</p>
使用前提 :在 app.module.ts 导入模块
typescript 运行
javascript
import { FormsModule } from '@angular/forms';
imports: [BrowserModule, FormsModule]
7. Angular 内置指令
分为 结构指令 (修改 DOM 结构)和 属性指令(修改 DOM 样式 / 属性)
7.1 结构指令
1. *ngIf 条件渲染
html 预览
ini
<div *ngIf="isShow">显示内容</div>
<div *ngIf="!isShow">隐藏内容</div>
2. *ngFor 列表渲染
html 预览
css
<ul>
<li *ngFor="let item of list; let i = index">
索引:{{ i }},内容:{{ item.name }}
</li>
</ul>
3. *ngSwitch 多条件判断
html 预览
xml
<div [ngSwitch]="status">
<p *ngSwitchCase="1">待支付</p>
<p *ngSwitchCase="2">已支付</p>
<p *ngSwitchDefault>未知状态</p>
</div>
7.2 属性指令
1. ngClass 动态类名
html 预览
css
<div [ngClass]="{ active: isActive, disabled: isDisabled }">
动态样式
</div>
2. ngStyle 动态样式
html 预览
css
<div [ngStyle]="{ color: 'red', fontSize: '20px' }">
内联样式
</div>
8. 事件绑定与用户交互
8.1 基础事件绑定
html 预览
xml
<!-- 点击事件 -->
<button (click)="handleClick()">点击</button>
<!-- 输入事件 -->
<input (input)="handleInput($event)" />
<!-- 表单提交 -->
<form (ngSubmit)="handleSubmit()"></form>
8.2 事件对象
typescript 运行
javascript
handleInput(e: Event) {
const value = (e.target as HTMLInputElement).value;
console.log(value);
}
9. 组件通讯(核心)
9.1 父组件 → 子组件(@Input)
子组件
typescript 运行
kotlin
import { Component, Input } from '@angular/core';
@Component({ selector: 'app-child' })
export class ChildComponent {
// 接收父组件数据
@Input() msg = '';
}
父组件模板
html 预览
xml
<app-child [msg]="父组件传递的数据"></app-child>
9.2 子组件 → 父组件(@Output + EventEmitter)
子组件
typescript 运行
typescript
import { Component, Output, EventEmitter } from '@angular/core';
export class ChildComponent {
@Output() sendMsg = new EventEmitter<string>();
sendToParent() {
this.sendMsg.emit('子组件传递的消息');
}
}
父组件
html 预览
bash
<app-child (sendMsg)="getMsg($event)"></app-child>
typescript 运行
typescript
getMsg(msg: string) {
console.log(msg);
}
9.3 兄弟组件通讯
步骤 1:创建消息服务
bash 运行
bash
ng g s services/message
typescript 运行
typescript
// message.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class MessageService {
// 订阅主体
private msgSubject = new Subject<any>();
// 发送消息
sendMessage(data: any) {
this.msgSubject.next(data);
}
// 接收消息
getMessage() {
return this.msgSubject.asObservable();
}
}
步骤 2:兄弟组件 A(发送方)
typescript 运行
typescript
// brother-a.component.ts
import { MessageService } from '../../services/message.service';
constructor(private msgService: MessageService) {}
sendBrotherMsg() {
this.msgService.sendMessage('来自兄弟A的消息');
}
html 预览
css
<button (click)="sendBrotherMsg()">发送给兄弟B</button>
步骤 3:兄弟组件 B(接收方)
typescript 运行
typescript
// brother-b.component.ts
import { MessageService } from '../../services/message.service';
import { Subscription } from 'rxjs';
msg = '';
sub!: Subscription;
constructor(private msgService: MessageService) {}
ngOnInit() {
// 订阅消息
this.sub = this.msgService.getMessage().subscribe(data => {
this.msg = data;
});
}
// 销毁时取消订阅(防内存泄漏)
ngOnDestroy() {
this.sub.unsubscribe();
}
html 预览
css
<p>接收兄弟消息:{{ msg }}</p>
步骤 4:父组件承载两个兄弟组件
html 预览
xml
<!-- parent.component.html -->
<app-brother-a></app-brother-a>
<app-brother-b></app-brother-b>
10. 服务与依赖注入 (Service)
typescript
运行
kotlin
// data.service.ts
@Injectable({ providedIn: 'root' })
export class DataService {
user = { name: 'Angular' };
getUser() { return this.user; }
}
组件使用
typescript
运行
typescript
constructor(private dataService: DataService) {}
ngOnInit() {
console.log(this.dataService.getUser());
}
11. 路由 (Routing) 基础
typescript
运行
css
// app-routing.module.ts
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: '**', component: HomeComponent }
];
html
预览
xml
<router-outlet></router-outlet>
<a routerLink="/home">首页</a>
10. 服务与依赖注入 (Service)
定义
服务用于封装公共逻辑(HTTP 请求、工具函数、全局状态),实现业务解耦。
10.1 创建服务
bash 运行
bash
ng g s services/data
10.2 服务示例
typescript 运行
kotlin
// data.service.ts
import { Injectable } from '@angular/core';
// 注入根组件(全局单例)
@Injectable({ providedIn: 'root' })
export class DataService {
// 公共数据
userInfo = { name: 'Angular用户' };
// 公共方法
getUserInfo() {
return this.userInfo;
}
}
10.3 组件使用服务(依赖注入)
typescript 运行
typescript
import { DataService } from '../../services/data.service';
export class HomeComponent {
// 依赖注入服务
constructor(private dataService: DataService) {}
ngOnInit() {
// 使用服务
const user = this.dataService.getUserInfo();
console.log(user);
}
}
11. 路由 (Routing) 基础
11.1 路由配置
typescript 运行
typescript
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { AboutComponent } from './components/about/about.component';
const routes: Routes = [
// 默认路由
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
// 404路由
{ path: '**', redirectTo: '/home' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
11.2 路由出口 + 路由跳转
html 预览
xml
<!-- 路由出口(渲染组件) -->
<router-outlet></router-outlet>
<!-- 声明式跳转 -->
<a routerLink="/home">首页</a>
<a routerLink="/about">关于</a>
<!-- 编程式跳转 -->
<button (click)="toAbout()">跳转到关于页</button>
typescript 运行
typescript
// 编程式导航
import { Router } from '@angular/router';
constructor(private router: Router) {}
toAbout() {
this.router.navigate(['/about']);
}
12. 表单开发(模板驱动 / 响应式)
12.1 模板驱动表单(简单表单)
html 预览
xml
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<input name="username" ngModel required placeholder="用户名">
<button type="submit">提交</button>
</form>
12.2 响应式表单(复杂表单,推荐)
导入模块
typescript 运行
javascript
import { ReactiveFormsModule } from '@angular/forms';
使用
typescript 运行
typescript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class LoginComponent {
loginForm: FormGroup;
constructor(private fb: FormBuilder) {
// 初始化表单
this.loginForm = this.fb.group({
username: ['', [Validators.required, Validators.minLength(2)]],
password: ['', [Validators.required]]
});
}
onSubmit() {
console.log(this.loginForm.value);
}
}
html 预览
xml
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<input formControlName="username">
<input formControlName="password">
<button type="submit" [disabled]="!loginForm.valid">提交</button>
</form>
13. HTTP 网络请求
13.1 导入模块
typescript 运行
javascript
import { HttpClientModule } from '@angular/common/http';
13.2 封装 HTTP 服务
typescript 运行
kotlin
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class HttpService {
constructor(private http: HttpClient) {}
// GET请求
getList(): Observable<any> {
return this.http.get('https://api.example.com/list');
}
// POST请求
addData(data: any): Observable<any> {
return this.http.post('https://api.example.com/add', data);
}
}
13.3 组件使用
typescript 运行
javascript
this.httpService.getList().subscribe({
next: (res) => console.log(res),
error: (err) => console.error(err)
});
14. 管道 (Pipe)
14.1 内置管道
html 预览
xml
<!-- 日期管道 -->
<p>{{ now | date:'yyyy-MM-dd' }}</p>
<!-- 大小写管道 -->
<p>{{ name | uppercase }}</p>
<!-- 小数管道 -->
<p>{{ num | number:'1.2-2' }}</p>
<!-- JSON管道 -->
<p>{{ obj | json }}</p>
14.2 自定义管道
示例 1:性别转换管道
bash 运行
css
ng g p pipes/sex-transform
typescript 运行
typescript
// sex-transform.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'sexTransform' })
export class SexTransformPipe implements PipeTransform {
// value:传入值,args:额外参数
transform(value: number): string {
switch (value) {
case 1: return '男';
case 2: return '女';
default: return '未知';
}
}
}
使用方式
html 预览
xml
<p>{{ 1 | sexTransform }}</p> <!-- 输出:男 -->
<p>{{ 2 | sexTransform }}</p> <!-- 输出:女 -->
示例 2:数组过滤管道
typescript 运行
typescript
// filter.pipe.ts
@Pipe({ name: 'filterList' })
export class FilterListPipe implements PipeTransform {
transform(list: any[], key: string, keyword: string): any[] {
if (!keyword) return list;
return list.filter(item => item[key].includes(keyword));
}
}
html 预览
ini
<li *ngFor="let item of list | filterList: 'name': keyword">{{item.name}}</li>
15. 组件生命周期钩子
15.1 Angular 共有 8 个生命周期钩子 ,按执行顺序排列,包含创建 / 更新 / 销毁全流程
typescript 运行
typescript
import {
Component,
OnChanges,
OnInit,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy,
Input
} from '@angular/core';
@Component({
selector: 'app-life-cycle',
template: `<p>{{ msg }}</p>`
})
export class LifeCycleComponent implements
OnChanges,
OnInit,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy {
@Input() msg = '测试';
// 1. 输入属性(@Input)改变时触发
ngOnChanges(): void {
console.log('1. ngOnChanges - 属性改变');
}
// 2. 组件初始化(最常用,请求数据)
ngOnInit(): void {
console.log('2. ngOnInit - 组件初始化完成');
}
// 3. 脏值检测(每次变更检测触发)
ngDoCheck(): void {
console.log('3. ngDoCheck - 变更检测');
}
// 4. 内容投影初始化完成
ngAfterContentInit(): void {
console.log('4. ngAfterContentInit - 内容投影初始化');
}
// 5. 内容投影变更检测
ngAfterContentChecked(): void {
console.log('5. ngAfterContentChecked - 内容检测');
}
// 6. 视图初始化完成(操作DOM)
ngAfterViewInit(): void {
console.log('6. ngAfterViewInit - 视图渲染完成');
}
// 7. 视图变更检测
ngAfterViewChecked(): void {
console.log('7. ngAfterViewChecked - 视图检测');
}
// 8. 组件销毁(清理定时器/订阅)
ngOnDestroy(): void {
console.log('8. ngOnDestroy - 组件销毁');
}
}
15.2 执行顺序
ngOnChanges→ 输入属性变化ngOnInit→ 初始化ngDoCheck→ 每次渲染检查ngAfterContentInit→ 内容投影ngAfterContentChecked→ 内容检查ngAfterViewInit→ DOM 渲染完成ngAfterViewChecked→ 视图检查ngOnDestroy→ 组件销毁
15.3 核心使用场景
ngOnInit:发起网络请求、初始化数据ngOnChanges:监听父组件传值变化ngAfterViewInit:操作 DOM 元素ngOnDestroy:清除定时器、取消订阅、防内存泄漏
16. 常用装饰器总结
表格
| 装饰器 | 作用 | 位置 |
|---|---|---|
| @Component | 定义组件 | 组件类 |
| @NgModule | 定义模块 | 模块类 |
| @Injectable | 定义服务 | 服务类 |
| @Input | 父传子 | 子组件属性 |
| @Output | 子传父 | 子组件事件 |
| @ViewChild | 获取 DOM / 子组件 | 组件属性 |
17. 项目打包与部署
17.1 生产打包
bash 运行
css
ng build --prod
# 或
ng build --configuration production
打包产物:dist/ 目录
17.2 部署
将 dist 目录静态文件部署到 Nginx、Apache、GitHub Pages 等平台。
18. 总结
本文覆盖了 Angular 入门所有核心基础知识点,包含:
- 环境搭建、模块 / 组件基础
- 模板语法、数据绑定、内置指令
- 组件通讯、服务注入、路由、表单、HTTP
- 生命周期、管道、打包部署
Angular 作为企业级框架 ,学习曲线略陡,但规范统一、生态完善、长期维护,非常适合中大型项目开发。掌握以上知识点,即可独立开发 Angular 中小型应用!