在 Angular 2 中將選擇元素繫結到物件

在 Angular 2 中將選擇元素繫結到物件

Angular 2 是一個流行的框架,用於建立 Web 應用程式。Angular 2 中最常見的任務之一是將選擇元素繫結到物件。

本文將學習如何使用 ng-forng-value 指令將選擇元素與 Angular 2 中的物件繫結。

使用 ng-forng-value 將選擇元素繫結到 Angular 2 中的物件

Ng-For 是一個內建的模板指令,它可以簡單地迴圈遍歷一組專案,例如陣列或物件,併為每個專案構建一個模板。

*ngFor="let <value> of <collection>"

ng-value 指令將選擇元素繫結到一個物件。它指定應該對映到選擇元素值的物件上的屬性名稱。

 <input ng-value="expression"></input>

有時,初學者會混淆 ng-valuevalue。因此,如果你在 Angular 2 中將選擇元素與物件繫結,你必須知道 ng-valuevalue 之間的區別。

Angular 中 ng-valuevalue 的區別

不同之處在於 value 始終是一個字串,而 ngValue 允許你傳遞一個物件。例如,你有一個用例,你需要在下拉選單中顯示專案的名稱。

並且當從選單中選擇單個物件時,你必須選擇物件的 id 來搜尋資料庫。在這種情況下使用 ngValue 會有所幫助,因為它需要一個物件。

此外,你要填充的物件模型應該在你的物件中定義。

點選這裡如果你想獲得更多關於 ng-value 的資訊。

在 Angular 2 中將選擇元素繫結到物件的步驟

下面給出了一些要遵循的基本步驟。

  1. ng-model 屬性新增到選擇元素。
  2. selected 屬性新增到你要繫結的物件。
  3. 使用花括號語法 {{obj.property}} 將物件屬性繫結到 select 元素。

讓我們舉一個例子來幫助我們詳細瞭解所有步驟。

首先,我們將建立一個名為 AppComponent 的元件。然後我們將建立一個名為 example 的介面物件,顯示 idname

在這種情況下,idname 都儲存字串。在上述兩個步驟之後,是時候通過新增一些資訊來修改選項了。

完整的 /app.component.ts 程式碼如下。

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


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Demo';

  selectedObject : example;
  SimpleExample = [
    {id: 'Welcome to New York City', name: 'New York'},
    {id: 'Welcome to Japan', name: 'Japan'},
    {id: 'Welcome to Singapore', name: 'Singapore'},
    {id: 'Welcome to Delft', name: 'Delft'}
  ]
}

interface example{
  id:string;
  name:string;
}

component.ts 檔案中,我們新增了一個變數 selectedObject,一個物件 example,我們將使用 ngModel 將它繫結到 select 元素。

另一個變數 SimpleExample 包含一組用於顯示 ngValue 選擇選項的物件。

完整的 /app.component.html 程式碼如下。

<h2>Angular 2 Select Example</h2>

<select [(ngModel)]="selectedObject">
<option *ngFor="let show of SimpleExample" [ngValue]="show">
{{show.name}}
</option>
</select>

{{selectedObject | json}}

example 物件現在已新增到 selectedObject。我們使用 JSON 管道來顯示它。

JSON 管道可以將輸入物件轉換為所需的結果,然後可以將其分配給變數或作為引數傳遞。它使用內建的 JavaScript 函式 JSON.stringify() 將資料轉換為 JSON 字串。

要了解有關 Angular JSON 管道的更多資訊,請單擊此處

我們得到上述示例的以下輸出。

輸出

點選這裡檢視上面提到的完整工作程式碼。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Muhammad Adil
Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook