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

新增導航

Adding navigation

本指南基於入門課程的第一步:基本 Angular 應用入門

This guide builds on the first step of the Getting Started tutorial, Get started with a basic Angular app.

在此階段,本線上商店應用會擁有基本的產品目錄。

At this stage of development, the online store application has a basic product catalog.

在以下各節中,你將嚮應用新增以下功能:

In the following sections, you'll add the following features to the application:

  • 在位址列中鍵入 URL 以導航到相應的產品頁面。

    Type a URL in the address bar to navigate to a corresponding product page.

  • 單擊頁面上的連結以在單頁應用中導航。

    Click links on the page to navigate within your single-page application.

  • 單擊瀏覽器的後退和前進按鈕以直觀地在瀏覽器的歷史記錄中瀏覽。

    Click the browser's back and forward buttons to navigate the browser history intuitively.

關聯 URL 路徑與元件

Associate a URL path with a component

本應用已經用 Angular Router 導航到了 ProductListComponent。本節將介紹如何定義顯示單個產品詳情的路由。

The application already uses the Angular Router to navigate to the ProductListComponent. This section shows you how to define a route to show individual product details.

  1. 產生用於展示產品詳情的新元件。在檔案列表中,右鍵單擊 app 資料夾,選擇 Angular GeneratorComponent。將元件命名為 product-details

    Generate a new component for product details. In the file list, right-click the app folder, choose Angular Generator and Component. Name the component product-details.

  2. app.module.ts 中,新增產品詳情的路由,其 pathproducts/:productId,其 componentProductDetailsComponent

    In app.module.ts, add a route for product details, with a path of products/:productId and ProductDetailsComponent for the component.

    src/app/app.module.ts
          
          @NgModule({
      imports: [
        BrowserModule,
        ReactiveFormsModule,
        RouterModule.forRoot([
          { path: '', component: ProductListComponent },
          { path: 'products/:productId', component: ProductDetailsComponent },
        ])
      ],
        
  3. 開啟 product-list.component.html

    Open product-list.component.html.

  4. 修改產品名稱上的連結,使其包括以 product.id 為引數的 routerLink

    Modify the product name anchor to include a routerLink with the product.id as a parameter.

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

    RouterLink 指令可幫助你自訂 a 元素。在這裡,路由或 URL 中包含一個固定的區段 /products。最後一段則是變數,插入當前產品的 id。 例如,id 為 1 的產品的 URL 是 https://getting-started-myfork.stackblitz.io/products/1

    The RouterLink directive helps you customize the anchor element. In this case, the route, or URL, contains one fixed segment, /products. The final segment is variable, inserting the id property of the current product. For example, the URL for a product with an id of 1 would be similar to https://getting-started-myfork.stackblitz.io/products/1.

  5. 透過單擊產品名稱,驗證路由器是否如預期般工作。應用中應該顯示 ProductDetailsComponent 元件,其顯示的內容為 “product-details works!”。

    Verify that the router works as intended by clicking the product name. The application should display the ProductDetailsComponent, which currently says "product-details works!"

    請注意,預覽視窗中的 URL 發生了變化。最後一個部分是 products/#,其中 # 表示你單擊的路由的編號。

    Notice that the URL in the preview window changes. The final segment is products/# where # is the number of the route you clicked.

檢視產品詳情

View product details

ProductDetailsComponent 會處理每個產品的顯示工作。Angular 路由器會根據瀏覽器的 URL 和你定義的路徑來顯示元件。

The ProductDetailsComponent handles the display of each product. The Angular Router displays components based on the browser's URL and your defined routes.

在本節中,你將使用 Angular 路由器來組合 products 資料和路由資訊以顯示每個產品的特定詳情。

In this section, you'll use the Angular Router to combine the products data and route information to display the specific details for each product.

  1. product-details.component.ts 中,從 @angular/router 匯入 ActivatedRoute,並從 ../products 匯入 products 陣列。

    In product-details.component.ts, import ActivatedRoute from @angular/router, and the products array from ../products.

    src/app/product-details/product-details.component.ts
          
          import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    
    import { Product, products } from '../products';
        
  2. 定義 product 屬性。

    Define the product property.

    src/app/product-details/product-details.component.ts
          
          export class ProductDetailsComponent implements OnInit {
      product: Product|undefined;
      /* ... */
    }
        
  3. 透過把 private route: ActivatedRoute 新增為建構函式括號內的引數,來把 ActivatedRoute 注入到 constructor() 中。

    Inject ActivatedRoute into the constructor() by adding private route: ActivatedRoute as an argument within the constructor's parentheses.

    src/app/product-details/product-details.component.ts
          
          export class ProductDetailsComponent implements OnInit {
      product: Product|undefined;
    
      constructor(
        private route: ActivatedRoute,
      ) { }
    
    }
        

    Angular 路由器載入的每個元件都有自己專屬的 ActivatedRouteActivatedRoute 中包含有關路由和路由引數的資訊。

    ActivatedRoute is specific to each component that the Angular Router loads. ActivatedRoute contains information about the route and the route's parameters.

    透過注入 ActivatedRoute,你可以配置此元件以使用服務。 管理資料那一步將更詳細地介紹服務。

    By injecting ActivatedRoute, you are configuring the component to use a service. The Managing Data step covers services in more detail.

  4. ngOnInit() 方法中,從路由引數中提取 productId,並在 products 陣列中找到相應的產品。

    In the ngOnInit() method, extract the productId from the route parameters and find the corresponding product in the products array.

    src/app/product-details/product-details.component.ts
          
          ngOnInit() {
      // First get the product id from the current route.
      const routeParams = this.route.snapshot.paramMap;
      const productIdFromRoute = Number(routeParams.get('productId'));
    
      // Find the product that correspond with the id provided in route.
      this.product = products.find(product => product.id === productIdFromRoute);
    }
        

    路由引數與你在此路由中定義的路徑變數相對應。要訪問路由引數,我們使用 route.snapshot ,它是一個 ActivatedRouteSnapshot,其中包含有關該特定時刻的活動路由資訊。與此路由匹配的 URL 提供了 productId。Angular 會使用 productId 來顯示每個唯一產品的詳情。

    The route parameters correspond to the path variables you define in the route. To access the route parameters, we use route.snapshot, which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.

  5. 更新 ProductDetailsComponent 的範本以顯示帶有 *ngIf 的產品詳情。如果產品存在,則此 <div> 會顯示名稱、價格和說明。

    Update the ProductDetailsComponent template to display product details with an *ngIf. If a product exists, the <div> renders with a name, price, and description.

    src/app/product-details/product-details.component.html
          
          <h2>Product Details</h2>
    
    <div *ngIf="product">
      <h3>{{ product.name }}</h3>
      <h4>{{ product.price | currency }}</h4>
      <p>{{ product.description }}</p>
    
    </div>
        

    <h4>{{ product.price | currency }}</h4> 這一行,使用 currency 管道將 product.price 從數字轉換為貨幣字串。管道是一種可以在 HTML 範本中轉換資料的方式。有關 Angular 管道的更多資訊,請參見管道

    The line, <h4>{{ product.price | currency }}</h4>, uses the currency pipe to transform product.price from a number to a currency string. A pipe is a way you can transform data in your HTML template. For more information about Angular pipes, see Pipes.

當用戶單擊產品列表中的名稱時,路由器會將其導航到產品的不同 URL,顯示此 ProductDetailsComponent,並展示產品詳情。

When users click on a name in the product list, the router navigates them to the distinct URL for the product, shows the ProductDetailsComponent, and displays the product details.

有關 Angular 路由器的更多資訊,請參見路由與導航

For more information about the Angular Router, see Routing & Navigation.

下一步是什麼

What's next

你已經配置好了應用,以便檢視產品詳情,每個產品詳情都有一個不同的 URL。

You have configured your application so you can view product details, each with a distinct URL.

繼續探索 Angular:

To continue exploring Angular:

  • 繼續管理資料以新增購物車功能、管理購物車資料並檢索外部資料以獲取運費。

    Continue to Managing Data to add a shopping cart feature, manage cart data, and retrieve external data for shipping prices.

  • 跳至部署以將你的應用部署到 Firebase 或轉為本地開發。

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