【Angular 5】數據綁定、事件綁定和雙向綁定

本文爲Angular5的學習筆記,IDE使用Visual Studio Code,內容是關於數據綁定,包括Property Binding、Class Binding、Style Binding。 css

在Angular裏,有兩種綁定,一種是數據綁定(Data Binding),另外一種是事件綁定(Event Binding)。html

數據流從類到視圖則是數據綁定,即在類中改變變量的值,UI視圖會跟着改變;反之,事件綁定是隨着觸發UI視圖,類中也會產生相應的變化,好比鼠標點擊、鍵盤點擊觸發事件。雙向綁定則是數據綁定+事件綁定的結合。下面講一一介紹數據綁定、事件綁定和雙向綁定。bootstrap

1、數據綁定 Data Binding瀏覽器

打開使用Angular CLI命令建立一個組件,命名爲testapp

ng g c test

文件根目錄以下:ide

app.component.x 系列爲頁面的根模塊,可由多個components組成,上述的test就是其中之一,每個component中包括屬於本身.html, .css,.ts文件,在根結構中能夠引用各個component。學習

app.component.ts 裏能夠定義元數據,好比@Component,其裏面的templateUrl、styleUrls會告訴 Angular 從哪裏獲取你爲組件指定html和css文件。this

方法一:spa

app.component.ts命令行

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

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

方法二:可使用在元數據裏的template和styles直接定義html和css,以下方式

app.component.ts

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

@Component({
  selector: 'app-root',
   template: `
    <h2> Welcome {{name}} </h2> ` , styles: [` .text-success { color : green; } .text-danger { color : red; } .text-special { font-style : italic; } `]
})
export class AppComponent {
  title = 'app';
}

若使用方法一,則能夠在其對應的html中,引用其餘模塊,好比test模塊,以標籤<app-test></app-test> 的方式嵌入。

app.component.html

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    From AppComponent!
  </h1>
  <app-test></app-test>
</div>

1. Property Binding

    Property Binding是對html中標籤屬性進行綁定,下面在test模塊下進行一系列綁定操做,在此模塊使用上述方法二對進行模塊開發,代碼皆在test.component.ts下編寫。

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

@Component({
  selector: 'app-test',
  template: `
    <h2>
      Welcome {{name}}
    </h2>
    <input id = {{myId}} type = "text" value = "Vishwas">
    <input [id] = "myId" type = "text" value = "Wish">
  `
 ,
  styles: [`
    .text-success {
      color : green;
    }
    .text-danger {
      color : red;
    }
    .text-special {
      font-style : italic;
    }
  `]
})
export class TestComponent implements OnInit {
 public name = "Dan"
 
  public myId = "testId"

  constructor() { }

  ngOnInit() {
  }

} 
[id] = "myId" 是把在TestComponent裏聲明的myId的值賦給html的相應標籤中id屬性,即id = "testId",並綁定該屬性。
在命令行內CLI輸入 ng serve,開啓http://localhost:4200/服務,在瀏覽器下訪問http://localhost:4200/,並對控件進行監測(inspect),效果以下,顯示爲 id = "testId",說明綁定成功!

2.  Class Binding

     Class Binding是對 css 中的class類進行綁定,方法和Property Binding類似。

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

@Component({
  selector: 'app-test',
  template: `
    <h2>
      Welcome {{name}}
    </h2>
    
    <input id = {{myId}} type = "text" value = "Vishwas">
    <input [id] = "myId" type = "text" value = "Wish">

    <h2 class="text-success">
      Convolution
    </h2>
    <h2 [class]="successClass">
      Convolution
    </h2>
    <h2 [class.text-danger] = "hasError">
      Convolution
    </h2>

    <h2 [ngClass]="messageClasses">
      Convolution
    </h2>
    `
 ,
  styles: [`
    .text-success {
      color : green;
    }
    .text-danger {
      color : red;
    }
    .text-special {
      font-style : italic;
    }
  `]
})
export class TestComponent implements OnInit {

  public name = "Dan";
  public myId = "testId"

  public isDisabled = false;
  public successClass = "text-success"
  public hasError = true;
  public isSpecial = true;
  public messageClasses = { "text-success": !this.hasError, //false "text-danger": this.hasError, //true "text-special": this.isSpecial //true }
  constructor() { }

  ngOnInit() {
  }

}
[class.text-danger] = "hasError" 若hasError變量爲true,則應用text-danger,顯示爲紅色;不然,顯示爲默認顏色,黑色。
[ngClass]="messageClasses"> 只應用messageClasses集合中結果爲true的類,若是有兩個以及的變量爲true,則同時應用於該標籤。必須"text-danger"和"text-special"爲true,顯示爲斜體紅色。

    效果圖以下:

3. Style Binding

   Style Binding是對 css 中的style進行綁定,方法和Class Binding類似。直接貼代碼:

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

@Component({
  selector: 'app-test',
  template: `
    <h2>
      Welcome {{name}}
    </h2>
        
    <h2 [style.color] = "hasError ? 'red':'green'">
      Style Binding
    </h2>

    <h2 [style.color] = "highlightColor">
      Style Binding2
    </h2>
    <h2 [ngStyle] = "titleStyles">
    Style Binding3
  </h2>

    `
 ,
  styles: []
})
export class TestComponent implements OnInit {

  public name = "Dan";
  public highlightColor = "orange"
  public titleStyles = { color: "blue", fontStyle: "italic" }
  constructor() { }

  ngOnInit() {
  }

}

    效果圖以下:

 

 

 

 

 

 

2、事件綁定和雙向綁定 Event Binding & Two Ways Binding

經過點擊按鈕,改變類中的變量,在呈現到視圖上,這個過程就是一種事件綁定。粉色代碼處爲事件綁定。

實時監視UI的控件,如有值的變化,變量能夠接收到此變化,並從新分配該值,再自動把該值更新到視圖,這就是雙向綁定。藍色代碼處爲雙向綁定。

temp.component.ts

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

@Component({
  selector: 'app-temp',
  template: `
    <button (click) = "onClick($event)">Greet</button>
    <button (click) = "greeting = 'inline Greet!!'">Greet2</button>
    <p>{{greeting}}</p>
    
    <input [(ngModel)] = "name" type="text"> {{name}}
  `,
  styles: []
})
export class TempComponent implements OnInit {

  public name = "";
  public greeting = ""; onClick(event){ this.greeting = 'Greeting!!'; //console.log(event);
 console.log(event.type); }

  constructor() { }

  ngOnInit() {
  }

}

 

Angular不能直接識別ngModel,須要經過一個單獨的模塊FormsModule來訪問,所以咱們要引用這個模塊,即在app.module.ts裏import  FormsModule,以下代碼:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';

import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { TempComponent } from './temp/temp.component';



@NgModule({
  declarations: [
    AppComponent,
    TestComponent,
    TempComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

效果圖以下:

 

本集完結,期待下一集,撒花~

相關文章
相關標籤/搜索