數(shù)據(jù)綁定
往AppComponent.ts中添加兩個(gè)屬性:title屬性用來(lái)顯示應(yīng)用名稱倦逐,hero屬性用來(lái)顯示英雄名稱
export class AppComponent{
title = 'my first angular project';
hero = 'yolanda';
}
更新@Component裝飾器中指定的模版损痰,為這些新屬性建立數(shù)據(jù)綁定
template:'<h1>{{title}}</h1><h2>{{hero}} details!</h2>'
雙括號(hào)是angular差值表達(dá)式綁定語(yǔ)法迹蛤,它表示組件的屬性title和hero的值會(huì)作為字符串插入到html標(biāo)簽中
hero對(duì)象
把hero從一個(gè)字符串字面量變成一個(gè)類,
創(chuàng)建一個(gè)Hero類,它具有id和name屬性争拐,下面是app.component.ts
import {Component} from @angular/core;
export class Hero{
id : Number;
name : String;
}
@Component({
selector:'app-root',
template:'.<h1>{{title}}</h1><h2>{{hero}} details!</h2>',
styleUrls:'./app.component.css'
})
export class appComponent{
title = 'Tours of heros';
hero : Hero = {
id: 1,
name : 'yolanda'
}
}
我們把hero從字符串變成了對(duì)象粮坞,也得更新模版中的綁定表達(dá)式,來(lái)引用hero中的name屬性
下面是app.component.html
template:'.<h1>{{title}}</h1><h2>{{hero.name}} details!</h2>'
多行模版顯示
反括號(hào)
template:`
<h1>title:{{title}}</h1>
<h2>hero:{{hero.name}}</h2>
`
雙向數(shù)據(jù)綁定
重構(gòu)app.component.ts的模版
<div style="text-align:center">
<h1>
{{title}}!
</h1>
<h2>{{hero.name}} detail!</h2>
<label>name:</label>
<input [(ngModel)]="hero.name" placeholder="name">
</div>
ngModel是一個(gè)有效的指令赤拒,它默認(rèn)情況下是不可用的秫筏,它屬于一個(gè)可選模塊FormsModel
需要在app.module.ts中import
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; 添加這一行
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule 在這里引入
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
總結(jié)
- {{}}花括號(hào)插值表達(dá)式(單向數(shù)據(jù)綁定的一種形式)
- 使用ES2015模版字符串(反引號(hào))寫了一個(gè)多行模版
- 為了同時(shí)顯示和修改英雄名字,使用了內(nèi)置指令ngModel挎挖,往input元素上添加了雙向設(shè)計(jì)綁定
- ngModel指令將修改傳播到每一個(gè)hero.name其他綁定
公眾號(hào):前端咖秀