Angular 2 数据绑定


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

假设如果你有一个类名,一个有类型和值的属性。

export class className {
    property: propertytype = value;
}

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

<html tag htmlproperty = 'property'>

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

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

步骤 1 : 下载任意2张图片。对于这个例子,我们将下载一些如下所示的简单图像。

Images Download

步骤 2 : 将这些图像存储在一个名为 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