html编辑器+angular,Angular Hero Editor 编辑器

本文通过一个示例详细介绍了如何在Angular2中实现数据双向绑定和单向绑定,同时利用ES6的模板字符串语法。首先创建AppComponent并设置title和hero属性,然后在模板中展示这些属性。接着将hero属性从字符串转为接口,更新模板以显示所有hero属性。最后通过修改模板,使用ngModel指令实现了数据的双向绑定。整个过程展示了Angular2核心的绑定概念和ES6的新特性应用。
摘要由CSDN通过智能技术生成

在这一个示例中可以学习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 hero

System.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!

id: {{hero.id}}

name:

name: {{hero.name}}
` //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:`

{{title}}

{{hero.name}} details!

id: {{hero.id}}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值