目录

angular2 - 数据绑定( Data Binding)

双向绑定是Angular JS中的一项功能,但已从Angular 2.x开始删除。 但是现在,自Angular 2中的类事件发生以来,我们可以绑定到AngularJS类中的属性。

假设您有一个具有类名的类,一个具有类型和值的属性。

export class className {
   property: propertytype = value;
}

然后,您可以将html标记的属性绑定到类的属性。

<html tag htmlproperty = 'property'>

然后将属性的值分配给html的html属性。

让我们看一下如何实现数据绑定的示例。 在我们的示例中,我们将查看显示图像,其中图像源将来自我们class中的属性。 以下是实现此目标的步骤。

Step 1 - 下载任意2张图片。 在本例中,我们将下载如下所示的一些简单图像。

图像下载

Step 2 - 将这些图像存储在app目录中名为Images的文件夹中。 如果图像文件夹不存在,请创建它。

Step 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'
   } ];
}

Step 4 - 在app.component.html中添加以下内容,如下所示。

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

在上面的app.component.html文件中,我们正在访问类中属性的图像。

输出 (Output)

上述程序的输出应该是这样的 -

数据绑定
↑回到顶部↑
WIKI教程 @2018