首页 > 建站教程 > 前端框架 >  Angular 5数据绑定、事件绑定和双向绑定正文

Angular 5数据绑定、事件绑定和双向绑定

在Angular里,有两种绑定,一种是数据绑定(Data Binding),另一种是事件绑定(Event Binding)。


Angular 5数据绑定、事件绑定和双向绑定


数据流从类到视图则是数据绑定,即在类中改变变量的值,UI视图会跟着改变;反之,事件绑定是随着触发UI视图,类中也会产生相应的变化,比如鼠标点击、键盘点击触发事件。双向绑定则是数据绑定+事件绑定的结合。下面讲一一介绍数据绑定、事件绑定和双向绑定。


一、数据绑定 Data Binding

打开使用Angular CLI命令创建一个组件,命名为test

1ng g c test


文件根目录如下:

Angular 5数据绑定、事件绑定和双向绑定


app.component.x 系列为页面的根模块,可由多个components组成,上述的test就是其中之一,每一个component中包括属于自己.html, .css,.ts文件,在根结构中可以引用各个component。

app.component.ts 里可以定义元数据,比如@Component,其里面的templateUrl、styleUrls会告诉 Angular 从哪里获取你为组件指定html和css文件。


方法一:

app.component.ts

01import { Component } from '@angular/core';
02  
03@Component({
04  selector: 'app-root',
05  templateUrl: './app.component.html',
06  styleUrls: ['./app.component.css']
07})
08export class AppComponent {
09  title = 'app';
10}


方法二:可以使用在元数据里的template和styles直接定义html和css,如下方式

app.component.ts

01import { Component } from '@angular/core';
02@Component({
03  selector: 'app-root',
04  template: `
05    <h2>
06      Welcome {{name}}
07    </h2>
08  `
09 ,
10  styles: [`
11    .text-success {
12      color : green;
13    }
14    .text-danger {
15      color : red;
16    }
17    .text-special {
18      font-style : italic;
19    }
20  `]
21})
22export class AppComponent {
23  title = 'app';
24}


若使用方法一,则可以在其对应的html中,引用其他模块,比如test模块,以标签<app-test></app-test> 的方式嵌入。

app.component.html

1<div style="text-align:center">
2  <h1>
3    From AppComponent!
4  </h1>
5  <app-test></app-test>
6</div>


二、属性绑定 Property Binding

Property Binding是对html中标签属性进行绑定,下面在test模块下进行一系列绑定操作,在此模块使用上述方法二对进行模块开发,代码皆在test.component.ts下编写。

01import { Component, OnInit } from '@angular/core';
02  
03@Component({
04  selector: 'app-test',
05  template: `
06    <h2>
07      Welcome {{name}}
08    </h2>
09    // [id] = "myId" 是把在TestComponent里声明的myId的值赋给html的相应标签中id属性,即id = "testId",并绑定该属性。
10    <input id = {{myId}} type = "text" value = "Vishwas">
11    <input [id] = "myId" type = "text" value = "Wish">
12  `
13 ,
14  styles: [`
15    .text-success {
16      color : green;
17    }
18    .text-danger {
19      color : red;
20    }
21    .text-special {
22      font-style : italic;
23    }
24  `]
25})
26export class TestComponent implements OnInit {
27 public name = "Dan"
28  
29  public myId = "testId"
30  
31  constructor() { }
32  
33  ngOnInit() {
34  }
35}


在命令行内CLI输入 ng serve,开启http://localhost:4200/服务,在浏览器下访问http://localhost:4200/,并对控件进行监测(inspect),效果如下,显示为 id = "testId",说明绑定成功!

Angular 5数据绑定、事件绑定和双向绑定


三、class类绑定 Class Binding

Class Binding是对 css 中的class类进行绑定,方法和Property Binding相似。

01import { Component, OnInit } from '@angular/core';
02  
03@Component({
04  selector: 'app-test',
05  template: `
06    <h2>
07      Welcome {{name}}
08    </h2>
09  
10    <input id = {{myId}} type = "text" value = "Vishwas">
11    <input [id] = "myId" type = "text" value = "Wish">
12  
13    <h2 class="text-success">
14      Convolution
15    </h2>
16    <h2 [class]="successClass">
17      Convolution
18    </h2>
19    // [class.text-danger] = "hasError" 若hasError变量为true,则应用text-danger,显示为红色;否则,显示为默认颜色,黑色。
20    <h2 [class.text-danger] = "hasError">
21      Convolution
22    </h2>
23  
24 // [ngClass]="messageClasses" 只应用messageClasses集合中结果为true的类,如果有两个以及的变量为true,则同时应用于该标签。必须"text-danger"和"text-special"为true,显示为斜体红色。
25    <h2 [ngClass]="messageClasses">
26      Convolution
27    </h2>
28    `
29 ,
30  styles: [`
31    .text-success {
32      color : green;
33    }
34    .text-danger {
35      color : red;
36    }
37    .text-special {
38      font-style : italic;
39    }
40  `]
41})
42export class TestComponent implements OnInit {
43  
44  public name = "Dan";
45  public myId = "testId"
46  
47  public isDisabled = false;
48  public successClass = "text-success"
49  public hasError = true;
50  public isSpecial = true;
51  public messageClasses = {
52    "text-success": !this.hasError, //false
53    "text-danger"this.hasError,  //true
54    "text-special"this.isSpecial //true
55  }
56  constructor() { }
57  
58  ngOnInit() {
59  }
60  
61}


效果图如下:

Angular 5数据绑定、事件绑定和双向绑定


四、style样式绑定 Style Binding

Style Binding是对 css 中的style进行绑定,方法和Class Binding相似。直接贴代码:

01import { Component, OnInit } from '@angular/core';
02  
03@Component({
04  selector: 'app-test',
05  template: `
06    <h2>
07      Welcome {{name}}
08    </h2>
09  
10    <h2 [style.color] = "hasError ? 'red':'green'">
11      Style Binding
12    </h2>
13  
14    <h2 [style.color] = "highlightColor">
15      Style Binding2
16    </h2>
17    <h2 [ngStyle] = "titleStyles">
18    Style Binding3
19  </h2>
20  
21    `
22 ,
23  styles: []
24})
25export class TestComponent implements OnInit {
26  
27  public name = "Dan";
28  public highlightColor = "orange"
29  public titleStyles = {
30    color: "blue",
31    fontStyle: "italic"
32  }
33  constructor() { }
34  
35  ngOnInit() {
36  }
37  
38}


效果图如下:

Angular 5数据绑定、事件绑定和双向绑定


五、事件绑定和双向绑定 Event Binding & Two Ways Binding

通过点击按钮,改变类中的变量,在呈现到视图上,这个过程就是一种事件绑定。粉色代码处为事件绑定。

实时监视UI的控件,若有值的变化,变量可以接收到此变化,并重新分配该值,再自动把该值更新到视图,这就是双向绑定。蓝色代码处为双向绑定。


temp.component.ts

01import { Component, OnInit } from '@angular/core';
02  
03@Component({
04  selector: 'app-temp',
05  template: `
06    <button (click) = "onClick($event)">Greet</button>
07    <button (click) = "greeting = 'inline Greet!!'">Greet2</button>
08    <p>{{greeting}}</p>
09  
10    <input [(ngModel)] = "name" type="text">
11    {{name}}
12  `,
13  styles: []
14})
15export class TempComponent implements OnInit {
16  
17  public name = "";
18  public greeting = "";
19  
20  onClick(event){
21    this.greeting = 'Greeting!!';
22    //console.log(event);
23    console.log(event.type);
24  }
25  
26  constructor() { }
27  
28  ngOnInit() {
29  }
30  
31}


Angular不能直接识别ngModel,需要通过一个单独的模块FormsModule来访问,因此我们要引用这个模块,即在app.module.ts里import  FormsModule,如下代码:


app.module.ts

01import { BrowserModule } from '@angular/platform-browser';
02import { NgModule } from '@angular/core';
03import {FormsModule} from '@angular/forms';
04  
05import { AppComponent } from './app.component';
06import { TestComponent } from './test/test.component';
07import { TempComponent } from './temp/temp.component';
08  
09@NgModule({
10  declarations: [
11    AppComponent,
12    TestComponent,
13    TempComponent
14  ],
15  imports: [
16    BrowserModule,
17    FormsModule
18  ],
19  providers: [],
20  bootstrap: [AppComponent]
21})
22export class AppModule { }


效果图如下:

Angular 5数据绑定、事件绑定和双向绑定