前言
我們使用如下的組件代碼進(jìn)行本文的所有演示
export class AppComponent {
angularLogo = 'https://angular.io/assets/images/logos/angular/angular.svg';
userName="David";
newItem() {
console.log("Hello world!");
}
}
組件到DOM - Component to DOM
屬性綁定,單向數(shù)據(jù)綁定。可以有下面三種不同的書寫方式。
< img src="{{ angularLogo }}">
< img [src]="angularLogo">
< img bind-src="angularLogo">
- 使用字符串插值方式。
{{ 變量名 }} - 使用方挎號
[],方挎號內(nèi)包含屬性名。 - 在屬性名前添加
bind-也可以達(dá)到同樣的效果。
DOM到組件 - DOM to Component
事件綁定,當(dāng)發(fā)生特定的DOM事件(例如:click,change,keyup)時(shí),調(diào)用組件中指定方法。在下面的示例中,單擊按鈕時(shí)調(diào)用該組件的newItem()方法:
<button (click)="newItem()"></button>
雙向數(shù)據(jù)綁定
使用[(ngModel)]="變量名"方式,可以實(shí)現(xiàn)雙向數(shù)據(jù)綁定。
<input type="text" [(ngModel)]="userName">
<h1>Hello {{userName}}!</h1>
從Angular 2.x版開始,Angular中的數(shù)據(jù)綁定真的只是歸結(jié)為屬性綁定和事件綁定。 雙向數(shù)據(jù)綁定是不存在的東西。 如果沒有ngModel指令,我們?nèi)绾螌?shí)現(xiàn)雙向數(shù)據(jù)綁定?如下所示:
<input [value]="username" (input)="username = $event.target.value">
<p>Hello {{username}}!</p>
我們來看看這里面發(fā)生了什么?
- [value]=”username” - 綁定變量
username到input元素的value屬性。 - (input)=”username = $event.target.value” - 綁定
input元素的input事件到j(luò)s代碼username = $event.target.value - $event - 在Angular的事件綁定中暴露的表達(dá)式,它的值為事件的載體。