Angular 2 - 資料繫結



雙向繫結是 AngularJS 中的一個功能,但在 Angular 2.x 及更高版本中已被移除。但是,現在由於 Angular 2 中類的出現,我們可以繫結到 AngularJS 類中的屬性。

假設你有一個類,它包含一個類名和一個具有型別和值的屬性。

export class className {
   property: propertytype = value;
}

然後,你可以將 html 標籤的屬性繫結到類的屬性。

<html tag htmlproperty = 'property'>

該屬性的值將被賦值給 html 的 html 屬性。

讓我們來看一個如何實現資料繫結的示例。在我們的示例中,我們將檢視顯示影像,其中影像源將來自我們類中的屬性。以下是實現此目的的步驟。

步驟 1 - 下載任意兩張圖片。在本例中,我們將下載下面顯示的一些簡單圖片。

Images Download

步驟 2 - 將這些圖片儲存在 app 目錄下的名為 Images 的資料夾中。如果 images 資料夾不存在,請建立它。

步驟 3 - 在 app.component.ts 中新增以下內容,如下所示。

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

@Component ({
   selector: 'my-app',
   templateUrl: 'app/app.component.html'
})

export class AppComponent {
   appTitle: string = 'Welcome';
   appList: any[] = [ {
      "ID": "1",
      "url": 'app/Images/One.jpg'
   },

   {
      "ID": "2",
      "url": 'app/Images/Two.jpg'
   } ];
}

步驟 4 - 在 app.component.html 中新增以下內容,如下所示。

<div *ngFor = 'let lst of appList'>
   <ul>
      <li>{{lst.ID}}</li>
      <img [src] = 'lst.url'>
   </ul>
</div>

在上面的 app.component.html 檔案中,我們正在訪問類中屬性的影像。

輸出

上述程式的輸出應如下所示:

Data Binding
廣告