在这一个示例中可以学习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: '<h1>{{title}}</h1><h2>{{hero}} details!</h2>'
})
//导出AppComponent 组件
export class AppComponent {
public title = 'Tour of Heroes';
public hero = 'Windstorm';
}
在项目根目录创建index.html
<html>
<head>
<title>tour of hero</title>
<!-- 1. Load libraries -->
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
在终端命令行中执行
$ 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: '<h1>{{title}}</h1><h2>{{hero}} details!</h2>'
})
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:`
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<div><label>name: </label>{{hero.name}}</div>
</div>` //es6 模板字符串语法
})
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:`
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<div><input [(ngModel)]="hero.name" placeholder="name"></div>
</div>
`
})
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