填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

什麼是 Angular?

What is Angular?

本主題會幫你瞭解 Angular:什麼是 Angular?它有哪些優勢?當建構應用時它能為你提供什麼幫助?

This topic can help you understand Angular: what Angular is, what advantages it provides, and what you might expect as you start to build your applications.

Angular 是一個基於 TypeScript 建構的開發平臺。它包括:

Angular is a development platform, built on TypeScript. As a platform, Angular includes:

  • 一個基於元件的框架,用於建構可伸縮的 Web 應用

    A component-based framework for building scalable web applications

  • 一組完美整合的函式庫,涵蓋各種功能,包括路由、表單管理、客戶端-伺服器通訊等

    A collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and more

  • 一套開發工具,可幫助你開發、建構、測試和更新程式碼

    A suite of developer tools to help you develop, build, test, and update your code

藉助 Angular,無論單人專案還是企業級應用,你都能獲得平臺帶來的優勢。 Angular 的設計目標之一就是讓更新更容易,因此你可以用最小的成本升級到最新的 Angular 版本。最重要的是,Angular 的生態系統由包括 170 萬名開發人員、函式庫作者和內容創作者在內的多元團隊構成。

With Angular, you're taking advantage of a platform that can scale from single-developer projects to enterprise-level applications. Angular is designed to make updating as easy as possible, so you can take advantage of the latest developments with a minimum of effort. Best of all, the Angular ecosystem consists of a diverse group of over 1.7 million developers, library authors, and content creators.

要試用包含本指南中程式碼片段的可工作範例,請看現場演練 / 下載範例

See the現場演練 / 下載範例for a working example containing the code snippets in this guide.

Angular 應用:知識要點

Angular applications: The essentials

本節會解釋 Angular 背後的核心思想。瞭解這些思想可以幫助你更有效地設計和建構應用。

This section explains the core ideas behind Angular. Understanding these ideas can help you design and build your applications more effectively.

元件

Components

元件是構成應用的磚塊。元件包括三個部分:帶有 @Component() 裝飾器的 TypeScript 類別、HTML 範本和樣式檔案。@Component() 裝飾器會指定如下 Angular 專屬資訊:

Components are the building blocks that compose an application. A component includes a TypeScript class with a @Component() decorator, an HTML template, and styles. The @Component() decorator specifies the following Angular-specific information:

  • 一個 CSS 選擇器,用於定義如何在範本中使用元件。範本中與此選擇器匹配的 HTML 元素將成為該元件的實例。

    A CSS selector that defines how the component is used in a template. HTML elements in your template that match this selector become instances of the component.

  • 一個 HTML 範本,用於指示 Angular 如何渲染此元件。

    An HTML template that instructs Angular how to render the component.

  • 一組可選的 CSS 樣式,用於定義範本中 HTML 元素的外觀。

    An optional set of CSS styles that define the appearance of the template's HTML elements.

下面是一個最小化的 Angular 元件。

The following is a minimal Angular component.

      
      import { Component } from '@angular/core';

@Component({
  selector: 'hello-world',
  template: `
    <h2>Hello World</h2>
    <p>This is my first component!</p>
    `,
})
export class HelloWorldComponent {
  // The code in this class drives the component's behavior.
}
    

要使用此元件,請在範本中編寫以下內容:

To use this component, you write the following in a template:

      
      <hello-world></hello-world>
    

當 Angular 渲染此元件時,產生的 DOM 如下所示:

When Angular renders this component, the resulting DOM looks like this:

      
      <hello-world>
    <h2>Hello World</h2>
    <p>This is my first component!</p>
</hello-world>
    

Angular 的元件模型提供了強大的封裝能力和直觀的應用結構。元件還能讓你的應用更容易進行單元測試,並可以提高程式碼的整體可讀性。

Angular's component model offers strong encapsulation and an intuitive application structure. Components also make your application easier to unit test and can improve the overall readability of your code.

有關可以用元件做什麼的更多資訊,請參見“元件”部分。

For more information on what you can do with components, see the Components section.

範本

Templates

每個元件都有一個 HTML 範本,用於宣告該元件的渲染方式。你可以內聯它或用檔案路徑定義此範本。

Every component has an HTML template that declares how that component renders. You define this template either inline or by file path.

Angular 使用額外的語法擴充套件了 HTML,使你可以從元件中插入動態值。當元件的狀態更改時,Angular 會自動更新已渲染的 DOM。此功能的應用之一是插入動態文字,如下例子所示。

Angular extends HTML with additional syntax that lets you insert dynamic values from your component. Angular automatically updates the rendered DOM when your component’s state changes. One application of this feature is inserting dynamic text, as shown in the following example.

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

這裡 message 的值來自元件類別:

The value for message comes from the component class:

      
      import { Component } from '@angular/core';

@Component ({
  selector: 'hello-world-interpolation',
  templateUrl: './hello-world-interpolation.component.html'
})
export class HelloWorldInterpolationComponent {
    message = 'Hello, World!';
}
    

當應用載入元件及其範本時,使用者將看到以下內容:

When the application loads the component and its template, the user sees the following:

      
      <p>Hello, World!</p>
    

注意這裡所用的雙花括號 —— 它們指示 Angular 對其中的內容進行插值。

Notice the use of double curly braces--they instruct Angular to interpolate the contents within them.

Angular 還支援屬性繫結,以幫助你設定 HTML 元素的 Property 和 Attribute 的值,並將這些值傳給應用的展示邏輯。

Angular also supports property bindings, to help you set values for properties and attributes of HTML elements and pass values to your application's presentation logic.

      
      <p [id]="sayHelloId" [style.color]="fontColor">You can set my color in the component!</p>
    

注意這裡所用的方括號 —— 該語法表明你正在將 Property 或 Attribute 繫結到元件類別中的值。

Notice the use of the square brackets--that syntax indicates that you're binding the property or attribute to a value in the component class.

你還可以宣告事件監聽器,來監聽並響應使用者的操作,例如按鍵、滑鼠移動、單擊和觸控等。你可以透過在圓括號中指定事件名稱來宣告一個事件監聽器:

You can also declare event listeners to listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches. You declare an event listener by specifying the event name in parentheses:

      
      <button (click)="sayMessage()" [disabled]="canClick">Trigger alert message</button>
    

前面的例子中呼叫了一個方法,該方法是在元件類別中定義的:

The preceding example calls a method, which is defined in the component class:

      
      sayMessage() {
    alert(this.message);
}
    

以下是在 Angular 範本中插值和繫結的例子:

The following is an example of interpolation and bindings within an Angular template:

      
      
  1. import { Component } from '@angular/core';
  2.  
  3. @Component ({
  4. selector: 'hello-world-bindings',
  5. templateUrl: './hello-world-bindings.component.html'
  6. })
  7. export class HelloWorldBindingsComponent {
  8. fontColor = 'blue';
  9. sayHelloId = 1;
  10. canClick = false;
  11. message = 'Hello, World';
  12. sayMessage() {
  13. alert(this.message);
  14. }
  15. }

你可以使用指令來為範本新增額外功能。 Angular 中最常用的指令是 *ngIf*ngFor 。你可以使用指令執行各種任務,例如動態修改 DOM 結構。你還可以用自訂指令來創建出色的使用者體驗。

You can add additional functionality to your templates through the use of directives. The most popular directives in Angular are *ngIf and *ngFor. You can use directives to perform a variety of tasks, such as dynamically modifying the DOM structure. And you can also create your own custom directives to create great user experiences.

以下程式碼是 *ngIf 指令的例子。

The following code is an example of the *ngIf directive.

      
      
  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'hello-world-ngif',
  5. templateUrl: './hello-world-ngif.component.html'
  6. })
  7. export class HelloWorldNgIfComponent {
  8. message = 'I\'m read only!';
  9. canEdit = false;
  10.  
  11. onEditClick() {
  12. this.canEdit = !this.canEdit;
  13. if (this.canEdit) {
  14. this.message = 'You can edit me!';
  15. } else {
  16. this.message = 'I\'m read only!';
  17. }
  18. }
  19. }

Angular 的宣告式範本使讓可以將應用的邏輯和外觀完全分開。範本基於標準 HTML,因此易於建構、維護和更新。

Angular's declarative templates allow you to cleanly separate your application's logic from its presentation. Templates are based on standard HTML, so they're easy to build, maintain, and update.

關於範本用法和用途的更多資訊,請參見“範本”部分。

For more information on what you can do with templates, see the Templates section.

依賴注入

Dependency injection

依賴注入讓你可以宣告 TypeScript 類別的依賴項,而無需操心如何實例化它們,Angular 會為你處理這些瑣事。這種設計模式能讓你寫出更加可測試、也更靈活的程式碼。儘管瞭解依賴注入對於開始用 Angular 並不是至關重要的事,但我們還是強烈建議你將其作為最佳實踐,並且 Angular 自身的方方面面都在一定程度上利用了它。

Dependency injection allows you to declare the dependencies of your TypeScript classes without taking care of their instantiation. Instead, Angular handles the instantiation for you. This design pattern allows you to write more testable and flexible code. Even though understanding dependency injection is not critical to start using Angular, we strongly recommend it as a best practice and many aspects of Angular take advantage of it to some degree.

為了說明依賴注入的工作原理,請考慮以下例子。第一個檔案 logger.service.ts 中定義了一個 Logger 類別。它包含一個 writeCount 函式,該函式將一個數字記錄到控制檯。

To illustrate how dependency injection works, consider the following example. The first file, logger.service.ts, defines a Logger class. This class contains a writeCount function that logs a number to the console.

      
      import { Injectable } from '@angular/core';

@Injectable({providedIn: 'root'})
export class Logger {
  writeCount(count: number) {
    console.warn(count);
  }
}
    

接下來,hello-world-di.component.ts 檔案中定義了一個 Angular 元件。該元件包含一個按鈕,它會使用此 Logger 類別的 writeCount 函式。要訪問此功能,可透過向建構函式中新增 private logger: Logger 來把 Logger 服務注入到 HelloWorldDI 類別中。

Next, the hello-world-di.component.ts file defines an Angular component. This component contains a button that uses the writeCount function of the Logger class. To access that function, the Logger service is injected into the HelloWorldDI class by adding private logger: Logger to the constructor.

      
      import { Component } from '@angular/core';
import { Logger } from '../logger.service';

@Component({
  selector: 'hello-world-di',
  templateUrl: './hello-world-di.component.html'
})
export class HelloWorldDependencyInjectionComponent  {
  count = 0;

  constructor(private logger: Logger) {
  }

  onLogMe() {
    this.logger.writeCount(this.count);
    this.count++;
  }
}
    

有關依賴注入和 Angular 的更多資訊,請參見 Angular 中的依賴注入部分。

For more information about dependency injection and Angular, see the Dependency injection in Angular section.

Angular CLI

Angular CLI 是開發 Angular 應用的最快、最簡單和推薦的方式。Angular CLI 能簡化許多工。這裡有些例子:

The Angular CLI is the fastest, easiest, and recommended way to develop Angular applications. The Angular CLI makes a number of tasks easy. Here are some examples:

ng build

把 Angular 應用編譯到一個輸出目錄中。

Compiles an Angular app into an output directory.

ng serve

建構你的應用並啟動開發伺服器,當有檔案變化時就重新建構。

Builds and serves your application, rebuilding on file changes.

ng generate

基於原理圖(schematic)產生或修改某些檔案。

Generates or modifies files based on a schematic.

ng test

在指定的專案上執行單元測試。

Runs unit tests on a given project.

ng e2e

建構一個 Angular 應用並啟動開發伺服器,然後執行端到端測試。

Builds and serves an Angular application, then runs end-to-end tests.

你會發現 Angular CLI 是建構應用的寶貴工具。

You'll find the Angular CLI a valuable tool for building out your applications.

有關 Angular CLI 的更多資訊,請參閱 “CLI 參考手冊”部分。

For more information about the Angular CLI, see the CLI Reference section.

自帶函式庫

First-party libraries

“Angular 應用:基本知識”部分提供了建構 Angular 應用時要用到的幾個關鍵架構元素的簡要描述。但是,當你的應用不斷成長並且想要新增其他功能(例如站點導航或使用者輸入)時,Angular 的許多優勢才會真正顯現出來。屆時,你可以透過 Angular 平臺,來引入 Angular 所提供的眾多自帶函式庫之一。

The section, Angular applications: The essentials, provides a brief overview of a couple of the key architectural elements you'll use when building Angular applications. But the many benefits of Angular really become apparent when your application grows and you want to add additional functions such as site navigation or user input. That's when you can leverage the Angular platform to incorporate one of the many first-party libraries that Angular provides.

你可以使用的一些函式庫包括:

Some of the libraries available to you include:

Angular 路由器

Angular Router

進階的客戶側導航功能與基於 Angular 元件的路由機制。支援延遲載入、巢狀路由、自訂路徑匹配規則等。

Advanced client-side navigation and routing based on Angular components. Supports lazy-loading, nested routes, custom path matching, and more.

Angular 表單

Angular Forms

統一的表單填報與驗證體系。

Uniform system for form participation and validation.

Angular HttpClient

健壯的 HTTP 客戶端函式庫,它可以支援更進階的客戶端-伺服器通訊。

Robust HTTP client that can power more advanced client-server communication.

Angular 動畫

Angular Animations

豐富的動畫體系,用於驅動基於應用狀態的動畫。

Rich system for driving animations based on application state.

Angular PWA

一些用於建構漸進式 Web 應用(PWA)的工具,包括 Service Worker 和 Web 應用清單(Manifest)。

Tools for building Progressive Web Applications (PWAs) including a service worker and Web app manifest.

Angular 原理圖

Angular Schematics

一些搭建腳手架、重構和升級的自動化工具。用於簡化大規模應用的開發。

Automated scaffolding, refactoring, and update tools that simplify development at large scale.

這些函式庫在擴充套件應用功能的同時,還能讓你將更多精力放在那些令你的應用與眾不同的功能上。你可以新增這些函式庫,並相信它們能與 Angular 框架無縫整合並同步更新。

These libraries expand your application's functionality while also allowing you to focus more on the features that make your application unique. And you can add these libraries knowing that they're designed to integrate seamlessly into and update simultaneously with the Angular framework.

只有當它們可以幫你嚮應用中新增功能或解決特定的問題時,你才需要這些函式庫。

These libraries are only required if and when they can help you add functionality to your applications or solve a particular problem.

下一步

Next steps

本主題旨在幫你瞭解 Angular:什麼是 Angular?它有哪些優勢?當建構應用時它能為你提供什麼幫助?

This topic is intended to give you a brief overview of what Angular is, the advantages it provides, and what you can expect as you start to build your applications.

要實際使用 Angular,請參閱我們的入門課程。本課程使用 stackblitz.com,因此你可以瀏覽 Angular 的可工作範例,而不必先做任何安裝工作。

To see Angular in action, see our Getting Started tutorial. This tutorial uses stackblitz.com, so you can explore a working example of Angular without any installation requirements.

為了進一步探索 Angular 的功能,我們建議你通讀《瞭解 Angular》 和《開發人員指南》這兩節。

To explore Angular's capabilities further, we recommend reading through the sections, Understanding Angular and Developer Guides.

最後複查時間: 3/8/2021