Angular 2 教程
Angular 2(以及后续版本)是 Google 发布的一个现代化的前端开发框架,专为构建动态的单页面应用程序(SPA)而设计。Angular 2 是从 AngularJS(1.x)中重构而来,提供了更高效、更模块化的解决方案。
以下是 Angular 2 的基础教程,涵盖了核心概念、组件、路由、表单等常用功能。
1. 设置 Angular 2 项目
1.1 安装 Node.js 和 npm
Angular 2 依赖 Node.js 和 npm。你需要先安装它们。
- 下载安装 Node.js,npm 会随 Node.js 一起安装。
1.2 使用 Angular CLI 创建项目
Angular CLI 是一个强大的命令行工具,可以帮助你快速创建 Angular 项目。
- 全局安装 Angular CLI:
npm install -g @angular/cli
- 创建一个新项目:
ng new my-angular-app
- 进入项目文件夹:
cd my-angular-app
- 启动开发服务器:
ng serve
- 在浏览器中访问 http://localhost:4200 查看你的应用。
2. 基本概念:组件(Component)
Angular 2 的核心构建块是 组件(Component)。组件将视图(HTML)和逻辑(TypeScript)结合在一起。
2.1 创建组件
Angular CLI 提供了命令来生成组件:
ng generate component my-component
这将会在 src/app
目录下创建 my-component
文件夹,并包含以下几个文件:
- my-component.component.ts:组件的 TypeScript 类文件。
- my-component.component.html:组件的 HTML 模板。
- my-component.component.css:组件的 CSS 样式。
- my-component.component.spec.ts:组件的单元测试文件。
2.2 示例组件代码
// my-component.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
message: string = 'Hello, Angular 2!';
}
<!-- my-component.component.html -->
<h1>{{ message }}</h1>
在 app.module.ts
中导入并声明组件:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MyComponent } from './my-component/my-component.component';
@NgModule({
declarations: [
AppComponent,
MyComponent
],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
3. 数据绑定
Angular 2 提供了多种数据绑定方式,用于视图和组件类之间的交互。
3.1 插值绑定(Interpolation Binding)
用于将数据从组件类绑定到视图:
<h1>{{ message }}</h1>
3.2 属性绑定(Property Binding)
将数据绑定到 HTML 元素的属性:
<img [src]="imageUrl">
3.3 事件绑定(Event Binding)
将组件类中的方法与 HTML 元素的事件(如 click
)绑定:
<button (click)="onClick()">Click Me</button>
3.4 双向数据绑定(Two-way Data Binding)
使用 ngModel
指令来实现双向数据绑定:
<input [(ngModel)]="name">
<p>{{ name }}</p>
4. 路由(Routing)
Angular 2 提供了内置的路由模块,帮助你实现单页面应用(SPA)的页面导航。
4.1 配置路由
首先,导入 RouterModule
:
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
定义路由规则:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
在 @NgModule
中导入路由模块:
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在模板中使用 routerLink
进行导航:
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
<router-outlet></router-outlet>
4.2 创建组件并设置路由
ng generate component home
ng generate component about
5. 表单(Forms)
Angular 2 提供了两种表单处理方式:模板驱动表单和响应式表单。
5.1 模板驱动表单
在模板中使用 ngModel
双向数据绑定和表单控件:
<form #myForm="ngForm">
<input [(ngModel)]="user.name" name="name" required>
<button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
5.2 响应式表单
在组件中创建表单控件并管理其状态:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', [Validators.required, Validators.minLength(4)]]
});
}
onSubmit() {
console.log(this.form.value);
}
}
在模板中:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input formControlName="name" />
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
6. 服务(Services)
服务是 Angular 2 中用于业务逻辑、数据共享等功能的核心部分。服务一般使用依赖注入(DI)来提供给组件。
6.1 创建服务
ng generate service user
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserService {
getUser() {
return { name: 'John Doe' };
}
}
6.2 在组件中使用服务
import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
user: any;
constructor(private userService: UserService) {
this.user = this.userService.getUser();
}
}
7. 使用依赖注入(DI)
Angular 的依赖注入允许你将服务、管道、指令等作为构造函数的依赖项注入到组件、服务或其他类中。
constructor(private http: HttpClient) {}
8. 管道(Pipes)
管道是 Angular 中的转换器,用于在模板中对数据进行转换(如日期、货币等)。
8.1 内置管道
date
:格式化日期。uppercase
:将文本转换为大写。currency
:格式化货币。
8.2 自定义管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent: string): number {
const exp = parseFloat(exponent);
return Math.pow(value, isNaN(exp) ? 1 : exp);
}
}
在模板中使用自定义管道:
<p>{{ 2 | exponentialStrength: 10 }}</p>
结语
Angular 2 提供了一个结构化、模块化且功能强大的前端开发框架。它包含了组件化、依赖注入、路由、表单验证、HTTP 请求等核心特性,适合构建复杂的单页面应用(SPA)。通过本教程,你可以快速入门并理解 Angular 2 的核心概念。
你可以进一步学习更多内容,如自定义指令、动画、国际化等,来增强你的 Angular 应用的功能。
发表回复