AngularJS 2.0 快速开始

AngularJS 2.0(现在通常称为 Angular,因为后续版本不再使用 2.x 这样的命名方式)是一个功能强大的前端框架,用于构建动态的 Web 应用程序。它提供了许多特性,如组件化开发、依赖注入、双向数据绑定等,能够帮助开发者高效地开发复杂的应用。本文将带你快速了解如何开始使用 Angular 进行开发。

目录#

  1. 环境准备
  2. 创建第一个 Angular 应用
  3. 组件的基本概念与使用
  4. 数据绑定
  5. 依赖注入
  6. 路由
  7. 最佳实践

1. 环境准备#

1.1 安装 Node.js#

Angular 开发依赖于 Node.js,你需要先从 Node.js 官网 下载并安装合适的版本。安装完成后,通过 node -vnpm -v 命令检查是否安装成功。

1.2 安装 Angular CLI#

Angular CLI(命令行界面)是官方提供的用于快速创建、开发和维护 Angular 应用的工具。在命令行中执行以下命令进行全局安装:

npm install -g @angular/cli

2. 创建第一个 Angular 应用#

2.1 使用 Angular CLI 创建项目#

打开命令行,进入你想要创建项目的目录,然后执行:

ng new my - angular - app

这会创建一个名为 my - angular - app 的新 Angular 项目。在创建过程中,你可以根据提示选择一些配置,如是否添加路由、使用哪种样式预处理器等。

2.2 运行应用#

进入项目目录:

cd my - angular - app

然后执行:

ng serve --open

ng serve 命令会启动开发服务器,--open 选项会自动在浏览器中打开应用,默认地址是 http://localhost:4200/

3. 组件的基本概念与使用#

3.1 组件是什么#

在 Angular 中,组件是构建应用的基本单元。一个组件由三部分组成:

  • 组件类(TypeScript 类):包含组件的逻辑,如属性、方法等。
  • 模板(HTML 文件):定义组件的视图结构。
  • 元数据(装饰器):使用 @Component 装饰器来配置组件,如指定模板文件路径、样式等。

3.2 创建组件#

使用 Angular CLI 创建组件非常简单,执行以下命令:

ng generate component my - component

这会在 src/app 目录下创建一个名为 my - component 的组件,包含 my - component.component.ts(组件类)、my - component.component.html(模板)、my - component.component.css(样式)等文件。

3.3 组件类示例#

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 from MyComponent!";
 
  sayHello() {
    console.log(this.message);
  }
}

3.4 模板示例(my - component.component.html)#

<h1>{{message}}</h1>
<button (click)="sayHello()">Say Hello</button>

这里使用了插值表达式 {{message}} 来显示组件类中的 message 属性,(click) 事件绑定来调用 sayHello 方法。

4. 数据绑定#

4.1 插值绑定#

如上面组件模板中的 {{message}},用于将组件类中的属性值显示在模板中。

4.2 属性绑定#

<img [src]="imageUrl" alt="My Image">

在组件类中定义 imageUrl 属性,[src] 会将组件类中的 imageUrl 值绑定到 img 标签的 src 属性上。

4.3 事件绑定#

<button (click)="onButtonClick()">Click Me</button>

(click) 会绑定按钮的点击事件到组件类中的 onButtonClick 方法。

4.4 双向数据绑定#

需要先导入 FormsModule(在 app.module.ts 中),然后在模板中使用 [(ngModel)]

<input [(ngModel)]="userName" type="text">
<p>You entered: {{userName}}</p>

在组件类中定义 userName 属性,这样输入框的值会和组件类中的 userName 保持同步。

5. 依赖注入#

5.1 为什么需要依赖注入#

依赖注入是 Angular 的一个核心特性,它可以让组件之间的依赖关系更加清晰和易于管理。例如,一个服务(如数据获取服务)可以通过依赖注入的方式提供给组件使用。

5.2 创建服务#

使用 Angular CLI 创建服务:

ng generate service my - service

my - service.service.ts 中编写服务逻辑,比如:

import { Injectable } from '@angular/core';
 
@Injectable({
  providedIn: 'root'
})
export class MyService {
  getData() {
    return "Some data from service";
  }
}

providedIn: 'root' 表示该服务在根模块中提供,整个应用都可以使用。

5.3 在组件中使用服务(依赖注入)#

在组件类中导入服务并在构造函数中注入:

import { Component } from '@angular/core';
import { MyService } from '../my - service.service';
 
@Component({
  selector: 'app - my - component',
  templateUrl: './my - component.component.html',
  styleUrls: ['./my - component.component.css']
})
export class MyComponent {
  dataFromService: string;
 
  constructor(private myService: MyService) {
    this.dataFromService = this.myService.getData();
  }
}

6. 路由#

6.1 配置路由#

首先在 app.module.ts 中导入 RouterModuleRoutes

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { RouterModule, Routes } from '@angular/router';
 
import { AppComponent } from './app.component';
import { MyComponent } from './my - component/my - component.component';
 
const routes: Routes = [
  { path: 'my - component', component: MyComponent },
  { path: '', redirectTo: '/my - component', pathMatch: 'full' }
];
 
@NgModule({
  declarations: [
    AppComponent,
    MyComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

这里定义了两条路由,一条指向 MyComponent,另一条是默认路由重定向。

6.2 使用路由#

在模板中使用 <router - outlet> 来显示匹配路由的组件视图,比如在 app.component.html 中:

<router - outlet></router - outlet>

还可以使用 <a> 标签的 routerLink 属性来创建导航链接:

<a [routerLink]="['/my - component']">Go to My Component</a>

7. 最佳实践#

7.1 模块化开发#

将应用按照功能划分成不同的模块,每个模块专注于特定的功能,使用 NgModule 来组织模块。

7.2 组件设计原则#

  • 保持组件单一职责,一个组件只做一件事。
  • 合理使用输入(@Input)和输出(@Output)属性来实现组件间的通信。

7.3 代码风格#

遵循 Angular 官方的代码风格指南,比如使用 TypeScript 的严格模式、合理命名等。

参考#

通过以上内容,你应该对 Angular 的快速开始有了基本的了解,可以进一步深入学习 Angular 的更多高级特性来构建复杂的应用。