Angular4學習筆記之DOM屬性綁定

簡介

使用插值表達式將一個表達式的值顯示在模版上css

<img src="{{imgUrl}}" alt="">
<h1>{{productTitle}}</h1>

使用方括號將HTML標籤的一個屬性值綁定到一個表達式上html

<img [src]="imgUrl" alt="">

使用小括號將組件控制器的一個方法綁定到模版上面的一個事件的處理器上segmentfault

<button (click)="onClickButton($event)">按鈕綁定事件</button>

注意

在開始下面的例子以前,請先確認已經新建了一個工程。若是沒有,請查看:Angular2學習筆記之Angular CLI 安裝和使用教程app

事件綁定

clipboard.png

準備工做dom

瞭解目的:在模版的界面上面增長一個按鈕,而後經過小括號綁定一個事件。
新建一個 bind 組件,使用命令:  ng g c bind

修改 bind.component.html學習

<!-- 界面增長代碼 -->
<button (click)="onClickButton($event)">按鈕綁定事件</button>

修改 bind.component.tsspa

//在 BindComponent 類方法中增長方法體
onClickButton(event: any){
  console.log(event);
}

修改 app.component.html翻譯

<!-- 增長 app-bind 組件 -->
<app-bind></app-bind>

圖示:code

clipboard.png

Dom屬性綁定

例子一

插值表達式 與 屬性綁定 之間的關係component

兩種方式均可以實現,angular 在實現的邏輯上面是: 在程序加載組件的時候,會先將 "插值表達式" 翻譯爲 "屬性綁定"

修改 bind.component.html

<!-- 界面增長代碼 -->

<!-- 屬性綁定 -->
<img [src]="imgUrl" alt="">

<!-- 插值表達式綁定 -->
<img src="{{imgUrl}}" alt="">

修改 bind.component.ts

//增長變量
imgUrl: string = "http://placehold.it/320x280";

圖示:

clipboard.png

例子二

dom 屬性 與 html 屬性的區別

HTML元素的 DOM屬性和 HTML 屬性是有部分區別的,這點須要明確差別。

修改 bind.component.html

<!-- 增長代碼 -->
<div>
  <input type="text" value="Tom" (input)="onInputEvent($event)">
</div>

修改 bind.component.ts

//增長 event事件
onInputEvent(event: any){
  //獲取的是 dom 屬性,即輸入屬性
  console.log(event.target.value);

  //獲取的是 html 屬性,也就是初始化的屬性
  console.log(event.target.getAttribute("value"));

}

圖示:

clipboard.png

總結:

1.少許的 HTML屬性和 DOM屬性之間有這 1 :1 的映射關係,如 :id
2.有些有 HTML屬性,沒有DOM 屬性, 如:colspan
3.有些有 DOM屬性,沒有HTML 屬性,如:textContent
4.就算名字同樣,DOM屬性和HTML屬性獲取的內容可能不同
5.模版綁定是經過DOM屬性綁定的,而不是經過HTML屬性
6.HTML屬性指定了初始值,DOM屬性表示當前值;DOM屬性的值能夠改變,HTML的值不能改變

例子部分完整代碼

bind.component.html

<p>
  bind works!
</p>

<button (click)="onClickButton($event)">按鈕綁定事件</button>

<div>
  <!-- 屬性綁定 -->
  <img [src]="imgUrl" alt="">

  <!-- 插值表達式綁定 -->
  <img src="{{imgUrl}}" alt="">
</div>

<div>
  <input type="text" value="Tom" (input)="onInputEvent($event)">
</div>

bind.component.ts

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

@Component({
  selector: 'app-bind',
  templateUrl: './bind.component.html',
  styleUrls: ['./bind.component.css']
})
export class BindComponent implements OnInit {

  imgUrl: string = "http://placehold.it/320x280";

  constructor() { }

  ngOnInit() {
  }

  onClickButton(event: any){
    console.log(event);
  }

  onInputEvent(event: any){
    //獲取的是 dom 屬性,即輸入屬性
    console.log(event.target.value);

    //獲取的是 html 屬性,也就是初始化的屬性
    console.log(event.target.getAttribute("value"));
  }
}
相關文章
相關標籤/搜索