在这一个示例中可以学习Angular2的数据双向绑定和数据的单向绑定,而且这个示例使用es6新特性模板字符串语法,环境的安装请参照第一章节
项目文件结构
angular2-tour-of-heroes
|—— node_modules
|—— app
| |——app.component.ts
| |——boot.ts
|——index.html
|——package.json
|——tsconfig.json
在我们app显示一些数据
现在添加一个组件AppComponent,这个组件包含两个属性title和hero属性 创建app.component.ts (AppComponent class)
//导出AppComponent 组件
export class AppComponent {
public title = 'Tour of Heroes';
public hero = 'Windstorm';
}
在组件中添加模板
//添加组件
@Component({
selector:'my-app',
template: '
{{title}}
{{hero}} details!
'})
//导出AppComponent 组件
export class AppComponent {
public title = 'Tour of Heroes';
public hero = 'Windstorm';
}
在项目根目录创建index.html
tour of heroSystem.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
Loading...
在终端命令行中执行
$ npm start
数据双向绑定
接下来我们需要给hero添加更多的属性,把hero文字字符串转换成接口
创建app.component.ts (Hero interface)
import {Component} from 'angular2/core';
//新增接口
interface Hero{
id:number,
name:string
}
@Component({
selector:'my-app',
template: '
{{title}}
{{hero}} details!
'})
export class AppComponent{
public title = 'tour of hero';
public hero:Hero = {
id:1,
name:'windstrom'
};
}
更改template显示hero所有的属性
import {Component} from 'angular2/core';
interface Hero{
id:number,
name:string
}
@Component({
selector:'my-app',
template:`
{{title}}
{{hero.name}} details!
name:
})
export class AppComponent{
public title = 'tour of hero';
public hero:Hero = {
id:1,
name:'windstrom'
};
}
此时,app实现所有hero属性的输出,但没有实现数据的双向绑定,这不是我们所期望的,现在只需要对template模板的简单修改即可实现双向绑定
import {Component} from 'angular2/core';
interface Hero {
id: number;
name: string;
}
@Component({
selector: 'my-app',
template:`
{{title}}
{{hero.name}} details!
name:
`
})
export class AppComponent {
public title = 'Tour of Heroes';
public hero: Hero = {
id: 1,
name: 'Windstorm'
};
}
$ npm start
现在我们可以看已经实现数据的双向绑定
总结
使用{{var}}可以展示hero对象的属性数据(单向数据绑定)
使用ES6模板字符串编写模板
使用ngModel指令和input元素实现数据双向绑定
ngModel 可以传播变化到绑定hero.name