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

Angular 入門

Getting started with Angular

Angular 歡迎你!

Welcome to Angular!

本課程將透過建構一個電子商務網站,向你介紹 Angular 的基本知識。該網站具有商品名錄、購物車和結賬表單。

This tutorial introduces you to the essentials of Angular by walking you through building an e-commerce site with a catalog, shopping cart, and check-out form.

為了幫助你更好地起步,本課程提供了一個已完成的應用,你可以在 Stackblitz 上試驗及互動,而不用建立本地開發環境。 StackBlitz 是一個基於瀏覽器的開發環境,你可以在其中使用各種技術來建立、儲存和共享專案。

To help you get started right away, this tutorial uses a ready-made application that you can examine and modify interactively on Stackblitz—without having to set up a local work environment. StackBlitz is a browser-based development environment where you can create, save, and share projects using a variety of technologies.

先決條件

Prerequisites

為了充分利用本課程,你應該已經對以下內容有基本的瞭解。

To get the most out of this tutorial you should already have a basic understanding of the following.

瀏覽範例應用

Take a tour of the example application

你可以用元件建構 Angular 應用。元件定義了 UI 中的職責範圍,讓你可以複用某些 UI 功能集。

You build Angular applications with components. Components define areas of responsibility in the UI that let you reuse sets of UI functionality.

一個元件由三部分組成:

A component consists of three things:

  • 處理資料和功能的元件類別

    A component class that handles data and functionality.

  • 決定 UI 的 HTML 範本

    An HTML template that determines the UI.

  • 定義外觀的元件專屬樣式

    Component-specific styles that define the look and feel.

本指南示範瞭如何使用下列元件建構應用。

This guide demonstrates building an application with the following components.

  • <app-root> - 第一個載入的元件,並且是其他元件的容器。

    <app-root>—the first component to load and the container for the other components.

  • <app-top-bar> - 商店名稱和結帳按鈕。

    <app-top-bar>—the store name and checkout button.

  • <app-product-list> - 產品列表。

    <app-product-list>—the product list.

  • <app-product-alerts> - 包含應用中各種通知的元件。

    <app-product-alerts>—a component that contains the application's alerts.

有關元件的更多資訊,請參見元件簡介

For more information about components, see Introduction to Components.

建立範例專案

Create the sample project

要建立範例專案,請在 StackBlitz 中產生一個預置的範例專案在 StackBlitz 中產生一個預置的範例專案。要儲存你的工作,請執行以下操作:

To create the sample project, generate theready-made sample project in StackBlitzready-made sample project in StackBlitz. To save your work:

  1. 登入到 StackBlitz。

    Log into StackBlitz.

  2. 對你產生的專案進行分支。

    Fork the project you generated.

  3. 定時儲存。

    Save periodically.

在 StackBlitz 中,右側的預覽窗格會顯示範例應用的啟動狀態。此預覽有兩個區域:

In StackBlitz, the preview pane on the right shows the starting state of the example application. The preview features two areas:

  • 帶有商店名稱(My Store)和 Checkout 按鈕的頂部欄

    a top bar with the store name, My Store, and a checkout button

  • 產品列表及其標題

    a header for a product list, Products

左側的專案區顯示了構成本應用的原始檔,包括基礎結構和配置檔案。

The project section on the left shows the source files that make up the application, including the infrastructure and configuration files.

當你產生本課程隨附的 StackBlitz 範例應用時,StackBlitz 會為你建立啟動程式檔案和模擬資料。本課程中用到的檔案位於 src 資料夾中。

When you generate the StackBlitz example applications that accompany the tutorials, StackBlitz creates the starter files and mock data for you. The files you use throughout the tutorial are in the src folder.

有關如何使用 StackBlitz 的更多資訊,請參見 StackBlitz 的文件

For more information on how to use StackBlitz, see the StackBlitz documentation.

建立產品列表

Create the product list

在本節中,你將修改應用以顯示產品列表。你會用到來自 products.ts 檔案的預定義產品資料,和一些來自 product-list.component.ts 檔案的方法。本節將指導你完成編輯 HTML(也稱為範本)的過程。

In this section, you'll update the application to display a list of products. You'll use predefined product data from the products.ts file and methods from the product-list.component.ts file. This section guides you through editing the HTML, also known as the template.

  1. product-list 資料夾中,開啟範本檔案 product-list.component.html

    In the product-list folder, open the template file product-list.component.html.

  2. <div> 上新增一個結構型指令 *ngFor,如下所示。

    Add an *ngFor structural directive on a <div>, as follows.

    src/app/product-list/product-list.component.html
          
          <h2>Products</h2>
    
    <div *ngFor="let product of products">
    </div>
        

    使用 *ngFor,會把這個 <div> 針對列表中的每個產品進行復寫。

    With *ngFor, the <div> repeats for each product in the list.

    結構型指令會透過新增、刪除和操作元素來調整或重塑 DOM 結構。有關結構型指令的更多資訊,請參見結構型指令

    Structural directives shape or reshape the DOM's structure, by adding, removing, and manipulating elements. For more information about structural directives, see Structural directives.

  3. 在此 <div> 中,新增 <h3>{{ product.name }}{{ product.name }} 語句是 Angular 插值語法的範例。插值 {{ }} 可以讓你把屬性值渲染為文字。

    Inside the <div>, add an <h3> and {{ product.name }}. The {{ product.name }} statement is an example of Angular's interpolation syntax. Interpolation {{ }} lets you render the property value as text.

    src/app/product-list/product-list.component.html
          
          <h2>Products</h2>
    
    <div *ngFor="let product of products">
    
      <h3>
          {{ product.name }}
      </h3>
    
    </div>
        

    預覽窗格將會更新,以顯示列表中每個商品的名稱。

    The preview pane updates to display the name of each product in the list.

  4. 為了讓每個商品名稱都能連結到商品詳情,請圍繞 {{ product.name }} 新增一個 <a> 元素。

    To make each product name a link to product details, add the <a> element around {{ product.name }}.

  5. 使用 [ ] 語法將標題設定為此產品的名稱,如下所示:

    Set the title to be the product's name by using the property binding [ ] syntax, as follows:

    src/app/product-list/product-list.component.html
          
          <h2>Products</h2>
    
    <div *ngFor="let product of products">
    
      <h3>
        <a [title]="product.name + ' details'">
          {{ product.name }}
        </a>
      </h3>
    
    </div>
        

    在預覽窗格中,將滑鼠懸停在產品名稱上,可以檢視所繫結的 name 屬性值,該值是產品名加上單詞 “details”。透過屬性繫結 [ ] 可以在範本表示式中使用屬性值。

    In the preview pane, hover over a product name to see the bound name property value, which is the product name plus the word "details". Property binding [ ] lets you use the property value in a template expression.

  6. 新增產品說明。在 <p> 元素上使用 *ngIf 指令,以便 Angular 只讓當前產品有描述 <p>

    Add the product descriptions. On a <p> element, use an *ngIf directive so that Angular only creates the <p> element if the current product has a description.

    src/app/product-list/product-list.component.html
          
          <h2>Products</h2>
    
    <div *ngFor="let product of products">
    
      <h3>
        <a [title]="product.name + ' details'">
          {{ product.name }}
        </a>
      </h3>
    
      <p *ngIf="product.description">
        Description: {{ product.description }}
      </p>
    
    </div>
        

    現在,該應用將在列表中顯示每個產品的名稱和描述。請注意,最後一項產品沒有描述段落。Angular 不會建立 <p> 元素,因為此產品的 description 屬性為空。

    The application now displays the name and description of each product in the list. Notice that the final product does not have a description paragraph. Angular doesn't create the <p> element because the product's description property is empty.

  7. 新增一個按鈕,以便使用者可以共享產品。將按鈕的 click 事件繫結到 product-list.component.ts 中的 share() 方法。事件繫結要在此事件用一組圓括號 ( ) 括起來,就比如 <button> 元素上的 (click)

    Add a button so users can share a product. Bind the button's click event to the share() method in product-list.component.ts. Event binding uses a set of parentheses, ( ), around the event, as in the (click) event on the <button> element.

    src/app/product-list/product-list.component.html
          
          <h2>Products</h2>
    
    <div *ngFor="let product of products">
    
      <h3>
        <a [title]="product.name + ' details'">
          {{ product.name }}
        </a>
      </h3>
    
      <p *ngIf="product.description">
        Description: {{ product.description }}
      </p>
    
      <button (click)="share()">
        Share
      </button>
    
    </div>
        

    每個產品現在都有一個 “Share” 按鈕。

    Each product now has a Share button.

    單擊 “Share” 按鈕將觸發一條通知,指出 “The product has been shared!”。

    Clicking the Share button triggers an alert that states, "The product has been shared!".

在編輯範本時,你已經瞭解了 Angular 範本的一些最常用的功能。更多資訊,請參閱元件和範本簡介

In editing the template, you have explored some of the most popular features of Angular templates. For more information, see Introduction to components and templates.

將資料傳遞給子元件

Pass data to a child component

目前,產品列表中顯示了每個產品的名稱和描述。ProductListComponent 還定義了一個 products 屬性,包含從 products.tsproducts 陣列匯入的各個產品的資料。

Currently, the product list displays the name and description of each product. The ProductListComponent also defines a products property that contains imported data for each product from the products array in products.ts.

下一步是建立一個新的通知功能,該功能會使用來自 ProductListComponent 的產品資料。通知會檢查產品的價格,如果價格大於 700 美元,則會顯示 Notify Me 按鈕,當產品上市銷售時,使用者可以透過該按鈕註冊通知。

The next step is to create a new alert feature that uses product data from the ProductListComponent. The alert checks the product's price, and, if the price is greater than $700, displays a Notify Me button that lets users sign up for notifications when the product goes on sale.

本節將引導你建立一個子元件 ProductAlertsComponent,該子元件可以從其父元件 ProductListComponent 接收資料。

This section walks you through creating a child component, ProductAlertsComponent that can receive data from its parent component, ProductListComponent.

  1. 右鍵單擊 app 資料夾,然後使用 Angular Generator 產生一個名為 product-alerts 的新元件。

    Right click on the app folder and use the Angular Generator to generate a new component named product-alerts.

    此產生器會為元件的三個部分建立初始檔案:

    The generator creates starter files for the three parts of the component:

    • product-alerts.component.ts
    • product-alerts.component.html
    • product-alerts.component.css
  2. 開啟 product-alerts.component.ts@Component() 裝飾器會指出它後面的類別是元件。@Component() 還會提供有關元件的元資料,包括其選擇器、範本和樣式。

    Open product-alerts.component.ts. The @Component() decorator indicates that the following class is a component. @Component() also provides metadata about the component, including its selector, templates, and styles.

    src/app/product-alerts/product-alerts.component.ts
          
          import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-product-alerts',
      templateUrl: './product-alerts.component.html',
      styleUrls: ['./product-alerts.component.css']
    })
    export class ProductAlertsComponent implements OnInit {
      constructor() { }
    
      ngOnInit() {
      }
    
    }
        

    @Component() 中的主要功能如下:

    Key features in the @Component() are as follows:

    • selectorapp-product-alerts)用於標識元件。按照慣例,Angular 元件選擇器以字首 app- 開頭,後跟元件名稱。

      The selector, app-product-alerts, identifies the component. By convention, Angular component selectors begin with the prefix app-, followed by the component name.

    • 範本和樣式檔名參考了元件的 HTML 和 CSS。

      The template and style filenames reference the component's HTML and CSS.

    • 這個 @Component() 定義還匯出了類別 ProductAlertsComponent,該類別會處理元件的功能。

      The @Component() definition also exports the class, ProductAlertsComponent, which handles functionality for the component.

  3. 要將 ProductAlertsComponent 設定為接收產品資料,請首先從 @angular/core 中匯入符號 Input

    To set up ProductAlertsComponent to receive product data, first import Input from @angular/core.

    src/app/product-alerts/product-alerts.component.ts
          
          import { Component, OnInit } from '@angular/core';
    import { Input } from '@angular/core';
    import { Product } from '../products';
        
  4. ProductAlertsComponent 類別定義中,使用 @Input() 裝飾器定義一個名為 product 的屬性。 @Input() 裝飾器指出此屬性值要從本元件的父元件 ProductListComponent 中傳入。

    In the ProductAlertsComponent class definition, define a property named product with an @Input() decorator. The @Input() decorator indicates that the property value passes in from the component's parent, ProductListComponent.

    src/app/product-alerts/product-alerts.component.ts
          
          export class ProductAlertsComponent implements OnInit {
      @Input() product!: Product;
      constructor() { }
    
      ngOnInit() {
      }
    
    }
        
  5. 開啟 product-alerts.component.html 並將佔位符段落替換為 Notify Me 按鈕,如果產品價格超過 700 美元,就會出現此按鈕。

    Open product-alerts.component.html and replace the placeholder paragraph with a Notify Me button that appears if the product price is over $700.

    src/app/product-alerts/product-alerts.component.html
          
          <p *ngIf="product.price > 700">
      <button>Notify Me</button>
    </p>
        
  6. 要將 ProductAlertsComponent 顯示為 ProductListComponent 的子級,請將選擇器 <app-product-alerts> 新增到 product-list.component.html 中。使用屬性繫結將當前產品作為輸入傳給此元件。

    To display ProductAlertsComponent as a child of ProductListComponent, add the selector, <app-product-alerts> to product-list.component.html. Pass the current product as input to the component using property binding.

    src/app/product-list/product-list.component.html
          
          <button (click)="share()">
      Share
    </button>
    
    <app-product-alerts
      [product]="product">
    </app-product-alerts>
        

這個新的產品通知元件將產品作為產品列表中的輸入。使用該輸入,它將根據產品的價格顯示或隱藏 Notify Me 按鈕。Phone XL 的價格超過了 700 美元,因此該產品上會顯示 Notify Me 按鈕。

The new product alert component takes a product as input from the product list. With that input, it shows or hides the Notify Me button, based on the price of the product. The Phone XL price is over $700, so the Notify Me button appears on that product.

將資料傳遞到父元件

Pass data to a parent component

為了使 Notify Me 按鈕起作用,子元件需要通知並將資料傳遞給父元件。當用戶單擊 Notify MeProductAlertsComponent 需要引發一個事件,並且 ProductListComponent 需要響應此事件。

To make the Notify Me button work, the child component needs to notify and pass the data to the parent component. The ProductAlertsComponent needs to emit an event when the user clicks Notify Me and the ProductListComponent needs to respond to the event.

  1. product-alerts.component.ts 中,從 @angular/core 匯入符號 OutputEventEmitter

    In product-alerts.component.ts, import Output and EventEmitter from @angular/core.

    src/app/product-alerts/product-alerts.component.ts
          
          import { Component } from '@angular/core';
    import { Input } from '@angular/core';
    import { Output, EventEmitter } from '@angular/core';
    import { Product } from '../products';
        
  2. 在元件類別中,使用 @Output() 裝飾器和 EventEmitter() 的實例定義一個名為 notify 的屬性。使用 @Output() 配置 ProductAlertsComponent,這會讓 ProductAlertsComponentnotify 屬性的值發生變化時引發一個事件。

    In the component class, define a property named notify with an @Output() decorator and an instance of EventEmitter(). Configuring ProductAlertsComponent with an @Output() allows the ProductAlertsComponent to emit an event when the value of the notify property changes.

    src/app/product-alerts/product-alerts.component.ts
          
          export class ProductAlertsComponent {
      @Input() product!: Product;
      @Output() notify = new EventEmitter();
    }
        

    在新元件中,Angular Generator 包括一個空的 constructor()、一個 OnInit 介面和 ngOnInit() 方法。由於這些步驟未使用到它們,因此以下程式碼範例為簡潔起見將其省略。

    In new components, the Angular Generator includes an empty constructor(), the OnInit interface, and the ngOnInit() method. Since these steps don't use them, the following code example omits them for brevity.

  3. product-alerts.component.html 中,修改 Notify Me 按鈕,增加事件繫結,並呼叫 notify.emit() 方法。

    In product-alerts.component.html, update the Notify Me button with an event binding to call the notify.emit() method.

    src/app/product-alerts/product-alerts.component.html
          
          <p *ngIf="product.price > 700">
      <button (click)="notify.emit()">Notify Me</button>
    </p>
        
  4. 定義使用者單擊按鈕時發生的行為。當子元件引發事件時,父元件 ProductListComponent(而不是 ProductAlertsComponent)會採取行動。在 product-list.component.ts 中,定義一個 onNotify() 方法,類似於 share() 方法。

    Define the behavior that happens when the user clicks the button. The parent, ProductListComponent—not the ProductAlertsComponent—acts when the child raises the event. In product-list.component.ts, define an onNotify() method, similar to the share() method.

    src/app/product-list/product-list.component.ts
          
          export class ProductListComponent {
      products = products;
    
      share() {
        window.alert('The product has been shared!');
      }
    
      onNotify() {
        window.alert('You will be notified when the product goes on sale');
      }
    }
        
  5. 更新 ProductListComponent,以從 ProductAlertsComponent 中接收資料。

    Update the ProductListComponent to receive data from the ProductAlertsComponent.

    product-list.component.html 中,將 <app-product-alerts> 繫結到產品列表元件的 onNotify() 方法。<app-product-alerts> 會顯示 Notify Me 按鈕的內容。

    In product-list.component.html, bind <app-product-alerts> to the onNotify() method of the product list component. <app-product-alerts> is what displays the Notify Me button.

    src/app/product-list/product-list.component.html
          
          <button (click)="share()">
      Share
    </button>
    
    <app-product-alerts
      [product]="product" 
      (notify)="onNotify()">
    </app-product-alerts>
        

  6. 單擊 Notify Me 按鈕以觸發一條通知,內容為:"You will be notified when the product goes on sale"。

    Click the Notify Me button to trigger an alert which reads, "You will be notified when the product goes on sale".

有關元件之間的通訊的更多資訊,請參見元件互動

For more information on communication between components, see Component Interaction.

下一步是什麼

What's next

在本節中,你已經建立了一個應用,該應用會遍歷資料,並讓特性元件彼此通訊。

In this section, you've created an application that iterates through data and features components that communicate with each other.

要繼續探索 Angular 並開發此應用,請執行以下操作:

To continue exploring Angular and developing this application:

  • 繼續進行應用內導航,以建立產品詳情頁。

    Continue to In-app navigation to create a product details page.

  • 跳至部署以轉為本地開發,或將你的應用部署到 Firebase 或你自己的伺服器上。

    Skip ahead to Deployment to move to local development, or deploy your application to Firebase or your own server.