1.Angular 基础


文档摘要

1.Angular 基础 Angular 基础 Angular 是一个流行的 TypeScript 框架,用于构建客户端 Web 应用程序。它提供了一个结构化的方式来组织代码,并提供了许多强大的功能,如组件化、依赖注入、数据绑定和路由。 1.1 Angular 架构概览 Angular 应用由多个核心概念组成,这些概念共同协作,构建出复杂的交互式用户界面。 核心概念: 组件 (Component): Angular 应用的基本构建块。一个组件包含: 模板 (Template): 定义组件的 HTML 视图。 类 (Class): 包含组件的逻辑和数据。 元数据 (Metadata): 提供关于组件的信息,例如选择器和模板 URL。

1.Angular 基础

1. Angular 基础

Angular 是一个流行的 TypeScript 框架,用于构建客户端 Web 应用程序。它提供了一个结构化的方式来组织代码,并提供了许多强大的功能,如组件化、依赖注入、数据绑定和路由。

1.1 Angular 架构概览

Angular 应用由多个核心概念组成,这些概念共同协作,构建出复杂的交互式用户界面。

graph TD A[Component] --> B(Template); A --> C(Class); A --> D(Metadata); E[Module] --> A; E --> F(Service); F --> G(Dependency Injection); H[Data Binding] --> A; I[Routing] --> A; J[HttpClient] --> F; K[RxJS] --> F; style A fill:#f9f,stroke:#333,stroke-width:2px style E fill:#ccf,stroke:#333,stroke-width:2px style F fill:#ccf,stroke:#333,stroke-width:2px subgraph Angular Application A E F H I J K end

核心概念:

  • 组件 (Component): Angular 应用的基本构建块。一个组件包含:

    • 模板 (Template): 定义组件的 HTML 视图。

    • 类 (Class): 包含组件的逻辑和数据。

    • 元数据 (Metadata): 提供关于组件的信息,例如选择器和模板 URL。

  • 模块 (Module): 将组件、服务和其他相关代码组织成逻辑单元。每个 Angular 应用至少有一个根模块 (AppModule)。

  • 服务 (Service): 提供可在整个应用程序中共享的功能,例如数据访问、日志记录或业务逻辑。

  • 依赖注入 (Dependency Injection): 一种设计模式,允许组件获取所需的依赖项,而无需自行创建。

  • 数据绑定 (Data Binding): 在组件的模板和类之间同步数据。

  • 路由 (Routing): 允许用户在应用程序的不同视图之间导航。

  • HttpClient: Angular提供的用于发起HTTP请求的模块。

  • RxJS: Angular使用 RxJS 作为其响应式编程库,用于处理异步操作和事件流。

1.2 创建 Angular 项目

要开始使用 Angular,首先需要安装 Angular CLI (命令行界面)。

npm install -g @angular/cli

安装完成后,可以使用以下命令创建一个新的 Angular 项目:

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

这将创建一个名为 "my-first-app" 的新项目,并启动一个开发服务器,在浏览器中打开应用程序。

1.3 组件详解

组件是 Angular 应用的核心。让我们创建一个简单的组件。

1. 创建组件文件:

src/app 目录下,创建一个名为 hello-world.component.ts 的文件:

import { Component } from '@angular/core'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent { message = 'Hello, Angular!'; }

代码解释:

  • @Component 装饰器:将类标记为 Angular 组件,并提供元数据。

    • selector: 指定在 HTML 中使用组件的标签。

    • templateUrl: 指向组件的 HTML 模板文件。

    • styleUrls: 指向组件的 CSS 样式文件。

  • HelloWorldComponent 类:包含组件的逻辑和数据。

    • message 属性:定义要在模板中显示的消息。

2. 创建模板文件:

src/app 目录下,创建一个名为 hello-world.component.html 的文件:

<p>{{ message }}</p>

代码解释:

  • {{ message }}:使用插值表达式,将组件类中的 message 属性的值显示在 HTML 中。

3. 创建样式文件 (可选):

src/app 目录下,创建一个名为 hello-world.component.css 的文件,可以添加组件的样式。

4. 在 AppModule 中声明组件:

打开 src/app/app.module.ts 文件,并进行如下修改:

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HelloWorldComponent } from './hello-world.component'; // 导入组件 @NgModule({ declarations: [ AppComponent, HelloWorldComponent // 声明组件 ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

代码解释:

  • declarations 数组:列出属于此模块的所有组件、指令和管道。

5. 在 AppComponent 中使用组件:

打开 src/app/app.component.html 文件,并进行如下修改:

<app-hello-world></app-hello-world>

代码解释:

  • <app-hello-world>:使用组件的选择器,将 HelloWorldComponent 嵌入到 AppComponent 的模板中。

现在,运行 ng serve --open,你应该能在浏览器中看到 "Hello, Angular!"。

1.4 数据绑定

Angular 提供了多种数据绑定方式,用于在组件的模板和类之间同步数据。

  • 插值 (Interpolation): 将组件类中的属性值显示在模板中。例如:{{ message }}

  • 属性绑定 (Property Binding): 将组件类中的属性值绑定到 HTML 元素的属性。例如:<img [src]="imageUrl">

  • 事件绑定 (Event Binding): 将 HTML 元素的事件绑定到组件类中的方法。例如:<button (click)="onClick()">Click me</button>

  • 双向绑定 (Two-way Binding): 在组件的模板和类之间双向同步数据。例如:<input [(ngModel)]="name">。 (需要导入 FormsModule 模块)

代码示例:

修改 hello-world.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent { message = 'Hello, Angular!'; imageUrl = 'https://via.placeholder.com/150'; isDisabled = false; name = ''; onClick() { this.message = 'Button clicked!'; } }

修改 hello-world.component.html

<p>{{ message }}</p> <img [src]="imageUrl"> <button (click)="onClick()" [disabled]="isDisabled">Click me</button> <input [(ngModel)]="name" placeholder="Enter your name"> <p>Hello, {{ name }}!</p>

1.5 指令 (Directives)

指令是 Angular 的另一个重要概念,用于扩展 HTML 的功能。Angular 提供了三种类型的指令:

  • 组件 (Component): 带有模板的指令。

  • 属性指令 (Attribute Directive): 修改现有 HTML 元素的行为或外观。

  • 结构指令 (Structural Directive): 通过添加、删除或替换 DOM 元素来改变 DOM 结构。

常用内置指令:

  • *ngIf: 根据条件显示或隐藏 DOM 元素。

  • *ngFor: 循环遍历集合,并为每个元素创建一个 DOM 元素。

  • [ngClass]: 动态地添加或删除 CSS 类。

  • [ngStyle]: 动态地设置元素的样式。

代码示例:

修改 hello-world.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent { message = 'Hello, Angular!'; imageUrl = 'https://via.placeholder.com/150'; isDisabled = false; name = ''; items = ['Item 1', 'Item 2', 'Item 3']; showItems = true; onClick() { this.message = 'Button clicked!'; } }

修改 hello-world.component.html

<p>{{ message }}</p> <img [src]="imageUrl"> <button (click)="onClick()" [disabled]="isDisabled">Click me</button> <input [(ngModel)]="name" placeholder="Enter your name"> <p>Hello, {{ name }}!</p> <div *ngIf="showItems"> <h3>Items:</h3> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> </div> <button (click)="showItems = !showItems">Toggle Items</button> <p [ngClass]="{'highlight': showItems, 'normal': !showItems}">This is a paragraph.</p>

1.6 服务和依赖注入

服务是提供可在整个应用程序中共享的功能的类。依赖注入是一种设计模式,允许组件获取所需的依赖项,而无需自行创建。

创建服务:

ng generate service my-service

这将创建一个名为 MyService 的服务。

修改 my-service.service.ts

import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyService { getData(): string { return 'Data from MyService!'; } }

代码解释:

  • @Injectable 装饰器:将类标记为可注入的服务。

    • providedIn: 'root':指定服务在根模块中提供,使其在整个应用程序中可用。

在组件中使用服务:

修改 hello-world.component.ts

import { Component, OnInit } from '@angular/core'; import { MyService } from './my-service.service'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent implements OnInit { message = 'Hello, Angular!'; imageUrl = 'https://via.placeholder.com/150'; isDisabled = false; name = ''; items = ['Item 1', 'Item 2', 'Item 3']; showItems = true; serviceData = ''; constructor(private myService: MyService) { } // 注入服务 ngOnInit() { this.serviceData = this.myService.getData(); } onClick() { this.message = 'Button clicked!'; } }

修改 hello-world.component.html

<p>{{ message }}</p> <img [src]="imageUrl"> <button (click)="onClick()" [disabled]="isDisabled">Click me</button> <input [(ngModel)]="name" placeholder="Enter your name"> <p>Hello, {{ name }}!</p> <div *ngIf="showItems"> <h3>Items:</h3> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> </div> <button (click)="showItems = !showItems">Toggle Items</button> <p [ngClass]="{'highlight': showItems, 'normal': !showItems}">This is a paragraph.</p> <p>Service Data: {{ serviceData }}</p>

代码解释:

  • constructor(private myService: MyService):在组件的构造函数中注入 MyService

  • ngOnInit():Angular 生命周期钩子,在组件初始化后调用。在这里,我们调用 myService.getData() 并将结果赋值给 serviceData 属性。

1.7 总结

本章节介绍了 Angular 的基础概念,包括组件、模块、服务、依赖注入、数据绑定和指令。通过代码示例,我们了解了如何创建 Angular 项目、组件和服务,以及如何使用数据绑定和指令来构建交互式用户界面。掌握这些基础知识对于深入学习 Angular 至关重要。

接下来可以学习 Angular 的路由、表单、HTTP 客户端等更高级的主题。


作者与出处
原作者: 灏天文库
来源:灏天文库
整理: 灏天文库整理
由灏天文库平台收录,内容或由平台用户上传,仅供学习交流
发布者: 作者: 灏天文库 转发
评论区 (0)
U